Skip to main content
Glama
README.md
# lbx-memory-service

Self-hosted long-term memory service for AI agents. It captures conversation
events, distills them into structured memories with an LLM, stores them in
SQLite with versioning and audit, and serves them back over REST and MCP.

自研通用 AI 记忆服务:SQLite 权威主库、user / project / org 三类长期作用域、
事件驱动蒸馏、版本化与审计、文本检索基线、REST / MCP 双入口,以及 OpenClaw
薄适配器。

> **Status: Phase 0 / alpha.** Single-user local pilot. The API, schema and
> extraction prompt may still change. It is not a multi-tenant production
> service yet.

## Features

- **7 memory types**: preference / fact / rule / decision / progress /
  experience / resource, each with a fixed identity key.
- **3 scopes**: user / project / org. Org knowledge is manual-import only.
- **Event-driven distillation**: explicit remember / correction / completed
  phase / decision / verified tool results; ordinary turns are evidence-only by
  default and can be opted into distillation.
- **Deterministic safety gates**: type-to-scope normalization, sensitivity and
  secret scanning, verbatim evidence quotes, policy and confidence thresholds.
- **Versioning and forgetting**: current / superseded / conflict versions,
  tombstones, audit trail.
- **Retrieval**: ACL first, then FTS5 trigram shortlist + weighted text/source/
  evidence/recency scoring, with a token budget.
- **Two entry points**: REST (`/api/v1/*`) and MCP (`/mcp`, streamable HTTP).
- **OpenClaw adapter**: recall before the prompt, capture after the reply,
  fail-open.

## Quick start

```bash
git clone https://github.com/zhangbaiwen77-oss/lbx-memory-service && cd lbx-memory-service
uv sync --extra dev
cp .env.example .env
# edit MEMORY_RUNTIME_TOKEN / MEMORY_ADMIN_TOKEN / MEMORY_LLM_*
uv run memory-service serve
```

Or with pip:

```bash
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
```

Health check: `GET http://127.0.0.1:8737/healthz`

OpenAPI docs: `http://127.0.0.1:8737/docs`

## Architecture

The full implementation guide (memory types, scopes, distillation pipeline,
storage schema, retrieval scoring, agent integration, evaluation) is in
[docs/memory-architecture-guide.html](docs/memory-architecture-guide.html).
A shorter markdown overview is in [docs/architecture.md](docs/architecture.md).

```text
OpenClaw turn
   ├─ before_prompt_build → memory-bridge recall → /memories:retrieve
   └─ user+assistant turn → classifyCapture → /memories:propose
                                                   ↓
                                         event_queue → worker → LLM
                                                   ↓
                                  memory_item / memory_version / memory_fts
```

## OpenClaw integration

The bridge plugin lives in the OpenClaw extension
`openclaw-memory-bridge`; this repository ships the Python adapter and harness
in `integrations/openclaw/`.

- Recall hook: `before_prompt_build` → `prependContext`
- Capture hooks: `message_received` / `message_sent`, with
  `before_agent_finalize` / `agent_end` fallbacks
- `captureMode`: `off` / `evidence` / `auto`
- MCP tools exposed as `memory_bridge__memory_search`,
  `memory_bridge__memory_propose`, etc.

See `integrations/openclaw/config.example.json` and the architecture guide.

## Evaluation

The distillation benchmark is synthetic and uses deterministic fact checks (no
LLM judge). Reports are written to `docs/` and are ignored by git because they
may contain local benchmark data.

```bash
uv run python tests/eval/openclaw_memory_eval.py --out-dir docs            # baseline
uv run python tests/eval/openclaw_memory_eval.py --out-dir docs --fixed    # fixes on
uv run python tests/eval/aggregate_openclaw_memory_eval.py                 # stability
uv run python tests/eval/compare_openclaw_memory_eval.py                   # before/after
uv run python tests/eval/run_eval.py                                       # retrieval baseline
```

Internal benchmark results are summarized in the architecture guide
(distillation 0.65 → 0.96 across 3 runs; retrieval exact/paraphrase recall@8
= 1.0, P95 4.53 ms). Those numbers come from an internal scenario set and are
not reproducible from this repository's synthetic harness.

## Optional capture expansion

Both switches default to `false`. If the memory service shares a gateway key
with the main chat, per-turn extraction can compete for concurrency; use a
separate key or raise the gateway limit first.

- `MEMORY_DISTILL_TURN_EVIDENCE=true`: ordinary `turn_evidence` turns enter the
  distillation queue instead of being evidence-only.
- `MEMORY_CONVERSATIONAL_EXPERIENCE_ACTIVE=true`: conversation-derived
  `experience` becomes active/recallable; default `false` stores it as a
  candidate for review.
- `MEMORY_KNOWN_KEYS_LIMIT=30`: existing identities shown to the extractor so
  it can reuse keys across sessions (dedup / revocation).

## API example

```bash
curl -s http://127.0.0.1:8737/api/v1/memories:retrieve \
  -H "Authorization: Bearer $MEMORY_RUNTIME_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"query":"回答风格","project_id":"local-project","scopes":["user","project"]}'
```

## Security and privacy

- **LLM egress**: event text is sent to the configured OpenAI-compatible
  endpoint for extraction. Do not point it at a provider you do not trust.
- **Local by default**: the server binds `127.0.0.1:8737`. Do not expose the
  stdio MCP transport to other users or hosts; HTTP transport requires a
  Bearer token.
- **Secrets**: credentials are read from environment variables only; `.env` and
  `data/` are ignored by git. Payloads are pre-scanned for hard-blocked secrets
  before leaving the machine.
- **Data at rest**: the SQLite file contains conversation-derived memories.
  Protect the file and backups accordingly.

See [SECURITY.md](SECURITY.md) for reporting and the threat model, and
[docs/limitations.md](docs/limitations.md) for known limitations.

## Configuration

See `.env.example`. All settings use the `MEMORY_` prefix.

## Contributing

Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) and
[CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md). Maintainers: see
[docs/RELEASING.md](docs/RELEASING.md) for the publish/release checklist.

## License

Apache License 2.0. See [LICENSE](LICENSE), [NOTICE](NOTICE), and
[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).

OpenClaw is a separate project (MIT licensed). This project is an independent
integration and is not affiliated with or endorsed by the OpenClaw project.