Metadata-Version: 2.5
Name: octop-memory
Version: 1.0.8
Summary: Pluggable memory system with hierarchical recall, FTS search, and multiple backend support.
Project-URL: Homepage, https://github.com/TencentCloud/octop-memory
Project-URL: Repository, https://github.com/TencentCloud/octop-memory
Project-URL: Documentation, https://github.com/TencentCloud/octop-memory/wiki
Project-URL: Discussions, https://github.com/TencentCloud/octop-memory/discussions
Project-URL: Issues, https://github.com/TencentCloud/octop-memory/issues
Project-URL: Changelog, https://github.com/TencentCloud/octop-memory/blob/main/CHANGELOG.md
Author: orcakit
License: MIT
License-File: LICENSE
Keywords: agent,fts,llm,mcp,memory,recall,sqlite
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT 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 :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.12
Provides-Extra: chroma
Requires-Dist: chromadb>=0.4; extra == 'chroma'
Provides-Extra: cli
Requires-Dist: click>=8.0; extra == 'cli'
Provides-Extra: dashboard
Requires-Dist: click>=8.0; extra == 'dashboard'
Requires-Dist: fastapi>=0.110; extra == 'dashboard'
Requires-Dist: uvicorn[standard]>=0.29; extra == 'dashboard'
Provides-Extra: embeddings
Requires-Dist: sentence-transformers>=2.2; extra == 'embeddings'
Provides-Extra: langgraph
Requires-Dist: langgraph-checkpoint-sqlite>=2.0; extra == 'langgraph'
Requires-Dist: langgraph-checkpoint>=2.0; extra == 'langgraph'
Provides-Extra: langgraph-postgres
Requires-Dist: langgraph-checkpoint-postgres>=2.0; extra == 'langgraph-postgres'
Requires-Dist: langgraph-checkpoint>=2.0; extra == 'langgraph-postgres'
Requires-Dist: psycopg[binary]>=3.1; extra == 'langgraph-postgres'
Provides-Extra: postgres
Requires-Dist: psycopg-pool>=3.2; extra == 'postgres'
Requires-Dist: psycopg[binary]>=3.1; extra == 'postgres'
Provides-Extra: qdrant
Requires-Dist: qdrant-client>=1.7; extra == 'qdrant'
Provides-Extra: server
Requires-Dist: click>=8.0; extra == 'server'
Requires-Dist: fastapi>=0.110; extra == 'server'
Requires-Dist: mcp<2,>=1.2; extra == 'server'
Requires-Dist: uvicorn[standard]>=0.29; extra == 'server'
Description-Content-Type: text/markdown

<p align="center">
  <img src="assets/images/banner.jpeg" alt="Octop Memory — a little octopus keeping memories safe" width="880" />
</p>

<p align="center">
  <strong>Help your agent remember what matters.</strong><br />
  Local-first, auditable, portable memory for LLM agents — share context across Claude Code, Cursor, Codex, OpenClaw, Hermes, and your own Python apps.
</p>

<p align="center">
  <a href="https://pypi.org/project/octop-memory/"><img alt="PyPI" src="https://img.shields.io/pypi/v/octop-memory?color=3776AB" /></a>
  <a href="pyproject.toml"><img alt="Python 3.12+" src="https://img.shields.io/badge/Python-3.12%2B-3776AB?logo=python&amp;logoColor=white" /></a>
  <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-E85D75" /></a>
  <a href="pyproject.toml"><img alt="Core dependencies: 0" src="https://img.shields.io/badge/Core_dependencies-0-E85D75" /></a>
  <a href="#optional-dependencies"><img alt="Storage: SQLite and PostgreSQL" src="https://img.shields.io/badge/Storage-SQLite_%7C_PostgreSQL-4169E1" /></a>
  <a href="https://github.com/TencentCloud/octop-memory/discussions"><img alt="GitHub Discussions" src="https://img.shields.io/github/discussions/TencentCloud/octop-memory?color=6e40c9" /></a>
  <a href="https://discord.gg/QnWdhJxq9h"><img alt="Discord" src="https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&amp;logoColor=white" /></a>
</p>

<p align="center">
  <a href="#highlights">Highlights</a> ·
  <a href="#quick-start">Quick start</a> ·
  <a href="#connect-coding-tools-mcp">MCP &amp; coding tools</a> ·
  <a href="#cli">CLI</a> ·
  <a href="#code-architecture">Architecture</a> ·
  <a href="#community">Community</a> ·
  <a href="CONTRIBUTING.md">Contributing</a> ·
  <a href="https://github.com/TencentCloud/octop-memory/wiki">Wiki</a>
</p>

<p align="center">
  <b>English</b> · <a href="README_CN.md">中文</a>
</p>

---

**Octop Memory** is a persistent, auditable, portable memory engine for LLM agents. Instead of dumping raw chat history into a black-box vector store, it separates raw evidence (`RawEvent`), reviewable candidates (`Candidate`), canonical facts (`AtomCard`), and conflict-replacement journals (`Journal`) — so your agent remembers preferences and project decisions, updates stale conclusions cleanly, and can always trace back to the original evidence.

Start locally with **zero core dependencies** (Python stdlib + SQLite/FTS5), run `octop-memory serve` to share one memory space across coding terminals over **HTTP MCP**, or scale to **PostgreSQL** and model-assisted extraction.

It powers memory in the [**Octop ecosystem**](https://github.com/TencentCloud/Octop) and runs independently as a Python library, CLI, standalone HTTP MCP service, or JSON-RPC bridge. Your host manages agent execution and model scheduling; Octop Memory handles capture, extraction, recall, storage, and migration.

> **Memory worth keeping. Context worth bringing along.** Save it, verify it, and carry it between supported agents.

<a id="highlights"></a>

## ✨ Highlights

| | What stands out | What you get |
|---|---|---|
| 🔌 | **Share memory across coding tools (MCP)** | Run `octop-memory serve` over HTTP MCP with per-client tokens, and wire **Claude Code, Codex, Cursor, Kiro, and DSH** into one shared space. |
| 🪶 | **Start small, add what you need** | Zero core dependencies: Python's standard library + SQLite/FTS5. Manual storage and lexical recall work out of the box without any LLM. |
| 🧠 | **Auditable experience governance** | Model-assisted extraction and promotion turn raw events into evidence-backed `AtomCard` facts, with conflict replacement and full `Journal` audit trails. |
| 🔍 | **Disciplined prompt recall** | Automatic prompt recall injects canonical atoms only (no raw-chat fallback pollution), bounded by ranking, deduplication, and token/time budgets; explicit tools search deeper on demand. |
| 🧳 | **Bring your memory along** | JSONL export/import and portable `.hmpkg` packages move accumulated memory across supported hosts, including **OpenClaw** and **Hermes**. |
| 💾 | **Local to server storage** | Start with a single SQLite file; scale to PostgreSQL with namespace isolation and bounded connection pools. |
| 🌳 | **Structured organization** | `AtomCard` facts, `EntityPage` summaries, `Episode` records, and a `root → branch → leaf` memory tree keep context navigable. |
| 🔖 | **Resume conversations** | Optional LangGraph checkpoints preserve execution state alongside long-term memory on SQLite or PostgreSQL. |

**Python 3.12+** is required. Automated extraction, promotion checks, and page regeneration use an injected `LLMClient`; installing the package alone does not configure a model. See the [integration guide](docs/integrations.md) for host setup, and read the [rename migration guide](docs/integrations.md#renaming-and-migrating-existing-installations) before upgrading pre-1.0 installations.

<a id="quick-start"></a>

## 🚀 Quick start

Current release: **1.0.8**. See [CHANGELOG.md](CHANGELOG.md) for release notes.

### Option A: Embed in Python (zero dependencies)

```bash
pip install octop-memory
```

```python
from octop_memory import Memory, MemoryService

memory = Memory(
    namespace="demo",
    backend_config={"db_path": "./demo.sqlite"},
)
memory.store("User prefers Python for backend services", topic="preferences")

# Since 1.0.4: explicit saves also accept kind="Fact" | "Preference" | "Decision" | "Task".
service = MemoryService(memory)
service.save("Use SQLite locally and PostgreSQL in staging", kind="Decision")

# Basic fact search returns MemoryNode leaf projections.
for node in memory.recall("Python"):
    print(node.content)

# Prompt recall adds source selection, ranking, deduplication, and budgeting.
result = service.recall("Python")
print(result.rendered)
```

This creates a local SQLite database. Use terms present in the stored text for a minimal FTS example. `Memory.search()` searches archived conversation messages and is a separate API from fact recall.

<a id="connect-coding-tools-mcp"></a>

### Option B: Share memory across Claude Code / Cursor / Codex (HTTP MCP)

Run a local standalone memory server and issue a scoped token per client:

```bash
pip install "octop-memory[server]"

octop-memory space create my-project --backend sqlite
octop-memory token create --space my-project --name claude-code --scope read,write
octop-memory serve --host 127.0.0.1 --port 8790
```

Then either install automatic recall + turn-capture hooks for **Claude Code, Codex, Cursor, Kiro, or DSH** in one command:

```bash
curl -fsSL https://raw.githubusercontent.com/TencentCloud/octop-memory/main/plugins/harness/install.sh \
  | sh -s -- --url http://127.0.0.1:8790/mcp/ --token omcp_…
```

Or add the Streamable HTTP MCP endpoint directly to any MCP client:

```json
{
  "mcpServers": {
    "octop-memory": {
      "type": "http",
      "url": "http://127.0.0.1:8790/mcp/",
      "headers": { "Authorization": "Bearer omcp_…" }
    }
  }
}
```

See the [standalone server guide](SERVER.md) for space management, token rotation/revocation, and the admin API, and [`plugins/harness/README.md`](plugins/harness/README.md) for terminal hook options and Windows PowerShell setup.

### Optional dependencies

| Install | Purpose |
|---|---|
| `pip install "octop-memory[cli]"` | CLI and OpenClaw setup commands |
| `pip install "octop-memory[server]"` | Standalone HTTP MCP memory service (`octop-memory serve`) |
| `pip install "octop-memory[postgres]"` | PostgreSQL memory backend |
| `pip install "octop-memory[langgraph]"` | SQLite LangGraph checkpointer |
| `pip install "octop-memory[langgraph-postgres]"` | PostgreSQL LangGraph checkpointer |

<details>
<summary>PostgreSQL setup, connection pooling, explicit save kinds, and vector index notes</summary>

- **Explicit save kinds (since 1.0.4):** `Memory.store(kind=...)` and `MemoryService.save(kind=...)` accept `"Fact"`, `"Preference"`, `"Decision"`, or `"Task"` without an extra model call (default `"Fact"`). Kind is independent of topic/entity type; existing facts are not reclassified, and saving a `Task` does not create a reminder. Releases up to v1.0.3 do not accept this keyword.
- **PostgreSQL backend:**
  ```python
  memory = Memory(
      namespace="demo",
      backend="postgres",
      backend_config={"dsn": "postgresql://user:pass@localhost/octop_memory"},
  )
  ```
  Inject real credentials from deployment configuration. SQLite isolates memory with table prefixes; PostgreSQL uses namespace-first keys in the shared `octop_memory` schema. Within one process, PostgreSQL instances with the same connection settings share a business pool (up to 8 connections) and a checkpoint/maintenance pool (up to 4), independent of agent count. Each pool allows at most 64 queued requests with a 30-second checkout timeout; saturation raises an explicit error. Idle pools can shrink to zero, and closing one instance leaves other instances usable. Budget separately for multiple processes, different connection settings, and the host's own database connections.
- **Optional vector indexes (experimental):** Vector search interfaces and Chroma/Qdrant adapters exist in the code, but current tests use fake/mock implementations; real Chroma/Qdrant integration remains unverified. Vector search is not enabled by default and is not yet presented as a fully supported installation option. Using it requires initializing an index and injecting `vector_index` and `embedding_provider` into `Memory`; installing dependencies alone does not enable it. The database backend remains `sqlite` or `postgres`.

</details>

## CLI

Install `[cli]` (or `[server]` for `serve` / `space` / `token`). Global options precede subcommands; examples explicitly select database and namespace.

```bash
octop-memory --db ./demo.sqlite --namespace demo memory store --content "User prefers Python"
octop-memory --db ./demo.sqlite --namespace demo recall "Python"
octop-memory --db ./demo.sqlite --namespace demo memory tree
octop-memory --help
```

| Commands | Purpose |
|---|---|
| `serve`, `space`, `token`, `auth` | Standalone HTTP MCP service and access tokens |
| `raw`, `candidate`, `atom`, `entity`, `page` | Inspect and manage memory layers |
| `episode`, `digest`, `journal` | Event summaries and decision audit records |
| `memory`, `recall`, `thread` | Tree operations, prompt recall, thread state |
| `export`, `import`, `migrate`, `portable` | Backup and cross-host migration |
| `db`, `gc`, `consolidate` | Storage maintenance and lifecycle operations |
| `config`, `openclaw`, `backfill` | Configuration, integration, historical extraction |

Run `<command> --help` for arguments. `db slim FILE` previews SQLite checkpoint deduplication; `--apply --offline` creates a backup and performs it without deleting history. Read [checkpoint compatibility and maintenance](CONTRIBUTING.md#checkpoint-maintenance) before migration or reader downgrade.

> Note: The local dashboard is available from a source checkout with `[dashboard]` dependencies; its modules are currently excluded from the wheel. Installing `octop-memory[dashboard]` from PyPI alone does not provide the dashboard command.

<a id="external-agent-adapters"></a>

## 🔌 External agent adapters

`plugins/<host>/` maps external agent hooks, tools, and configuration to the shared Python runtime or MCP service.

| Integration | Use case | Entry point |
|---|---|---|
| Standalone HTTP MCP | Shared memory space across multiple clients/terminals | `octop-memory serve` ([SERVER.md](SERVER.md)) |
| Terminal client hooks | Claude Code, Codex, Cursor, Kiro, DSH calling an Octop memory MCP | `plugins/harness` (`octop-memory-harness`) |
| Host plugin | Agent-specific lifecycle and tool interfaces | `plugins/<host>/`; OpenClaw and Hermes implemented |
| In-process Python | Custom agents / Python applications | `MemoryService.capture_turn()` / `recall()` / `search()` / `get()` / `extract()` |
| JSON-RPC bridge | Cross-language or separate processes | stdio `octopmemory-bridge` |

See the [integration guide](docs/integrations.md) for installation, configuration, profiles, troubleshooting, and adapter boundaries. Move memory between supported hosts with `octop-memory portable list-sources / pack / adopt / doctor` (keep exported `.hmpkg` files out of source control).

<a id="code-architecture"></a>

## 🧱 Code architecture

```text
src/octop_memory/
├── core.py / types.py     # Public Memory API and data structures
├── service.py            # MemoryService: Python host entry point
├── server/               # Standalone HTTP MCP service and admin API
├── application/          # MemoryRuntime, config, host files, path projection
├── pipeline/             # Extraction, promotion, recall, pages, episodes, lifecycle
├── storage/              # SQLite / PostgreSQL, checkpoints, vector indexes
├── ports/                # External capability interfaces, including LLM clients
├── domain/               # Shared alias and time rules
├── adapters/             # JSON-RPC bridge, CLI, source-only dashboard
└── operations/           # Import/export, migration, portable packages
plugins/                  # External agent adapters (harness, openclaw, hermes)
examples/                 # Public API example
tests/ / evals/           # Behavior tests / synthetic recall evaluation
docs/agent/               # Project map, ADRs, test matrix, and handoff
```

### Host call flow

```text
Python host → MemoryService ─────────┐
Hermes → in-process Bridge ──────────┤
OpenClaw → JSON-RPC bridge ───────────┼→ MemoryRuntime → pipelines → Memory
MCP clients → octop-memory serve ────┤                  ├→ SQLite / PostgreSQL
CLI → application / operations ──────┘                  └→ optional vector index
```

### Long-term memory flow

```text
RawEvent ──extraction──→ Candidate ──promotion──→ AtomCard ──dirty / regeneration──→ EntityPage
    └──episode extraction──→ Episode                └──atom_id reference──→ tree leaf
```

Candidates do not all require human approval: promotion checks value, evidence, entity resolution, duplicates, and conflicts to promote, merge, drop, or hold items for review. Facts live canonically in `AtomCard`; tree leaves reference atoms without copying facts. Manual `Memory.store()` needs no model and directly creates `RawEvent`/`Candidate`/`AtomCard` plus a leaf reference.

<details>
<summary>Governance, recall policy, runtime error filtering, and manual document contracts</summary>

- **Layer boundaries:** Adapters call inward through `application` and `pipeline`/`core`/`storage`. `MemoryService` and `Bridge` share `MemoryRuntime`; pipeline/storage do not depend on adapters, and backend-specific SQL stays in `storage` (the source-only dashboard's direct SQLite access is an existing exception). Hermes currently calls `Bridge` in-process; OpenClaw uses a bridge subprocess. `MemoryService.recall()` also calls the recall pipeline directly.
- **Atom-only automatic recall:** Automatic prompt recall uses canonical `atom` facts only, including optional vector atom hits. No matching atom means an empty result; raw conversations and page summaries are not injected as fallback. Explicit `MemoryService.search()` / `memory_search` keeps multi-source retrieval and its configurable raw policy. Low-level callers can opt into that behavior with `recall_for_prompt(..., atom_only=False)`; current-session raw remains excluded.
- **Entity disambiguation and value lookups:** Named queries search the entity and the global topic index. A fact held by another owner can enter the results when its text explicitly names the target; an ambiguous name leaves automatic recall empty. Run `octop-memory entity dream --limit 20` to audit existing atoms in the background and inspect evidence via `octop-memory journal list --action entity_review`. For common value lookups (e.g., phone numbers, attachment limits, log retention periods), lexical recall expands equivalent wording and checks that the fact supplies the requested value; the extractor can also index up to three alternative search phrases while prompts still cite the original assertion.
- **Runtime failure isolation:** Synthetic runtime failures are excluded from automatic capture, extraction, and raw prompt fallback. `octop-harness` / Octop surface model errors as checkpoint task failures; automatic team failure notifications are excluded from capture. Hosts that still create synthetic replies must mark them with `payload.octop_runtime_error=true`; online filtering uses structured provenance only. Agents decide when to call `memory_save`; approvals and manual saves are protected by their provenance, without intent or troubleshooting-value keyword lists. `operations.retention.audit_runtime_errors(memory)` previews eligible records by default; `apply=True` retires only automatic atoms whose evidence is entirely marked as runtime failures, while legacy retry envelopes and mixed/missing evidence remain in review lists.
- **Manual documents priority (ADR-042):** `MemoryService.reconcile_manual_documents({"USER.md": text, "MEMORY.md": text})` (and the matching Bridge methods) gives owner-edited documents priority. Proven conflicts softly retire the old atom and create a replacement review candidate with original evidence and a journal trail. Pass the session snapshot to `recall(..., manual_context=documents)` to suppress duplicate injection. `save`, extraction, and promotion do not run manual-document comparison synchronously; hosts call `MemoryService.review_new_memory(max_atoms=20)` on a background worker with `manual_documents_provider`. Explicit reconciliation checks up to 100 new facts per call (up to 100,000 document characters). Failed model batches defer and mark uncertain after 3 failures without forcing retirement; full documents are stored as comparison metadata, not indexed atoms.

</details>

<a id="community"></a>

## 💬 Community & ecosystem

We are building Octop Memory in the open — whether you want to submit a reproducible bad case report, connect a new agent host, or vote on the roadmap, you are very welcome here:

- **💡 [GitHub Discussions](https://github.com/TencentCloud/octop-memory/discussions)** — Ask questions, discuss unconfirmed bad cases & tuning ideas, vote on the public roadmap, share integrations/presets, or join the **Octop Memory Officers (记忆官)** program.
- **🧪 [Submit a Bad Case Report](https://github.com/TencentCloud/octop-memory/issues/new?template=bad_case_report.yml)** — Have a reproducible missed recall, noisy injection, stale conflict, or extraction error? Submit a sanitized Bad Case Report (`bad-case` label) — accepted cases (`eval-adopted`) enter our official regression suite with credit in [CHANGELOG.md](CHANGELOG.md) and [ACKNOWLEDGMENTS.md](ACKNOWLEDGMENTS.md)!
- **🎯 [Good First Issues](https://github.com/TencentCloud/octop-memory/labels/good%20first%20issue)** — Bite-sized tasks for first-time contributors.
- **💬 [Discord Community](https://discord.gg/QnWdhJxq9h)** — Join the Octop ecosystem Discord for real-time discussion.
- **📱 WeCom User Group (企业微信交流群)** — Scan the QR code below to connect with maintainers and fellow builders:

<p align="center">
  <img src="assets/images/community-qr.png" alt="Octop Community WeCom Group QR Code" width="200" />
</p>

### Related projects

| Project | Description |
|---|---|
| [Octop](https://github.com/TencentCloud/Octop) | Self-hosted multi-user, multi-agent AI assistant powered by Octop Memory |
| [Octop Harness](https://github.com/TencentCloud/octop-harness) | Agent runtime — model routing, tools, skills, and checkpoints |
| [Octop Gateway](https://github.com/TencentCloud/octop-gateway) | Multi-platform IM channel bridge |
| [Octop Browser](https://github.com/TencentCloud/octop-browser) | CDP browser automation with persistent profiles |

## 🤝 Contributing & development

First-time contributor? Start with the [5-minute quick path in CONTRIBUTING.md](CONTRIBUTING.md#quick-path-for-external-contributors) — you don't need to touch internal agent handoff docs for your first PR.
Architecture details live in [PROJECT_MAP](docs/agent/PROJECT_MAP.md), coding-agent rules in [AGENTS.md](AGENTS.md), and the full documentation index in [docs/README.md](docs/README.md).

```bash
make install          # uv sync --group dev
make install-hooks    # required once per clone
make all              # format + lint + strict mypy + tests
uv build              # Python wheel + sdist
```

Run PostgreSQL behavior tests against a real test server with `TEST_POSTGRES_DSN`; skipped PG cases do not prove compatibility. OpenClaw has its own `npm ci`, `npm test`, and `npm run build` under `plugins/openclaw/octopmemory/`.

### Contributors & acknowledgments

Thanks to everyone who has contributed PRs, bug reports, design feedback, and bad case reports to Octop Memory! See [ACKNOWLEDGMENTS.md](ACKNOWLEDGMENTS.md) for the full list including issue reporters and non-code contributors, and [CHANGELOG.md](CHANGELOG.md) for per-release credits.

<a href="https://github.com/TencentCloud/octop-memory/graphs/contributors">
  <img src="https://contrib.rocks/image?repo=TencentCloud/octop-memory" alt="Octop Memory contributors" />
</a>

## 📄 License

[MIT](LICENSE). Please follow our [Code of Conduct](CODE_OF_CONDUCT.md) and report security vulnerabilities privately via [SECURITY.md](SECURITY.md).
