Skip to main content
Glama
README.md
# Living Memory · الذاكرة الحية

**The durable mind layer for autonomous agents.**
A local-first memory system that lets an agent remember, reflect, and resume work across sessions — without starting from zero and without surrendering its memory to a vendor.

[![CI](https://github.com/pawloblock-byte/living-memory/actions/workflows/ci.yml/badge.svg)](https://github.com/pawloblock-byte/living-memory/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-22c55e.svg)](LICENSE)
[![Live demo](https://img.shields.io/badge/live-demo-7c5cff.svg)](https://pawloblock-byte.github.io/living-memory/)

**Live demo:** https://pawloblock-byte.github.io/living-memory/

> Runs entirely in your browser with a built-in simulated model. No API key, no account, no server needed to try it. Your memories stay in IndexedDB on your device.

---

## Why

Most agents have a context window, not a memory. When the window closes they forget decisions, preferences, and unfinished work. Living Memory gives them a small, honest, open memory layer:

- **Retain** — store facts, decisions, preferences, procedures and feedback.
- **Recall** — hybrid relevance: semantic similarity + recency + importance + reinforcement + tags.
- **Reflect** — compress episodes into durable semantic knowledge.
- **Maintain** — deduplicate, detect contradictions, decay, archive and purge.
- **Resume** — reconstruct project state, last session and next step for a new agent.

It is model-agnostic, self-hostable, and readable for decades (plain JSON/SQLite, no proprietary format).

## Core model

Every memory lives on **two axes** plus a lifecycle:

| Axis | Values |
| --- | --- |
| Type | `episodic`, `semantic`, `procedural`, `feedback` |
| Network | `world` (facts), `experience` (events), `observation` (inferred), `opinion` (beliefs) |
| Lifecycle | active → superseded / trashed → purged |

- **Deduplication**: near-identical memories (cosine ≥ 0.94 **and** token Jaccard ≥ 0.7) are merged instead of piled up.
- **Contradiction handling**: a new memory supersedes an old one only when it shares a subject/tag or uses an explicit change cue (`instead`, `moved to`, `switched`, `انتقل`, `بدل`, `تغير`, `الآن`, `لم يعد`). History is never silently overwritten — the old memory is kept with a `supersededBy` pointer.
- **Forgetting is a feature**: decay lowers salience, low-value items move to trash, trash is purged after a retention window. Pinned memories are protected.

## Features

- **Browser app** — React 19 + Vite, bilingual English/Arabic with full RTL, dark futuristic UI, mobile-first.
- **Local-first** — all state in IndexedDB; export/import the whole mind as JSON.
- **Encrypted secrets** — LLM API keys encrypted with AES-256-GCM using a non-extractable browser `CryptoKey`; file vault encrypted the same way.
- **Bring your own model** — OpenAI, Anthropic, Google, any OpenAI-compatible local server (Ollama, LM Studio, vLLM), or the built-in simulated adapter.
- **Server mode** — Fastify API with SQLite (default) or PostgreSQL, wallet/Google auth, per-user agents, and an MCP endpoint.
- **MCP** — expose memory to Claude Code / any MCP client over JSON-RPC (`initialize`, `tools/list`, `tools/call`).
- **Solana payments** — 7-day trial, then $19/month, paid on **mainnet-beta** and verified on-chain by the server before activation. The treasury address is never rendered in the UI.

## Quick start (web)

```bash
git clone https://github.com/pawloblock-byte/living-memory.git
cd living-memory
npm install
npm run dev            # http://localhost:5173
```

Build a static site:

```bash
npm run build          # apps/web/dist
npm run build:pages    # same, with base path /living-memory/
```

Open the app → *Continue with wallet* (Phantom/Solflare) or *Try the demo*. The demo seeds a sample project, session and memories so you can see recall, reflection and resume immediately.

## Quick start (API)

```bash
cp .env.example .env
npm run dev:api        # http://localhost:8787
curl http://localhost:8787/health
```

With no `DATABASE_URL`, data is stored in `./data/living-memory.sqlite` (via the built-in `node:sqlite`). Set `DATABASE_URL=postgres://…` for PostgreSQL.

### Auth

1. `POST /auth/nonce` → `{ nonce, message }`
2. Sign `message` with the wallet (ed25519).
3. `POST /auth/wallet` with `{ walletAddress, message, signature, nonce }` → `{ token }`
4. Send `Authorization: Bearer <token>` on every request.

Google sign-in: `POST /auth/google` with a Google ID token credential (verified against Google's `tokeninfo`; set `GOOGLE_CLIENT_ID` to enforce audience).

### Main endpoints

| Method | Path | Purpose |
| --- | --- | --- |
| GET | `/health` | liveness + backend info |
| POST | `/auth/nonce` · `/auth/wallet` · `/auth/google` | authentication |
| GET/POST | `/agents` | list/create agents |
| GET/POST | `/agents/:id/memory` | list / recall / retain |
| GET | `/agents/:id/memory/:mid` | one memory + links |
| POST | `/agents/:id/memory/:mid/pin\|trash\|restore\|purge` | lifecycle |
| GET | `/agents/:id/memory?query=…` | recall |
| GET | `/agents/:id/context?query=…` | prompt-ready context block |
| GET | `/agents/:id/resume` | project + session handoff |
| POST | `/agents/:id/chat` | chat with memory injection |
| POST/GET | `/agents/:id/maintenance/run\|reflect\|logs` | maintenance |
| GET/POST | `/agents/:id/projects`, `/sessions` | projects and sessions |
| GET | `/agents/:id/export` | export one agent's mind (JSON) |
| GET/POST | `/subscription`, `/subscription/activate` | trial + on-chain activation |
| POST | `/mcp` | MCP JSON-RPC endpoint |

### MCP client config

```json
{
  "mcpServers": {
    "living-memory": {
      "url": "https://your-host/mcp",
      "headers": { "Authorization": "Bearer <token>" }
    }
  }
}
```

Tools: `living_memory_retain`, `living_memory_recall`, `living_memory_reflect`, `living_memory_resume`, `living_memory_context`, `living_memory_stats`.

## Self-hosting with Docker

```bash
cp .env.example .env
# set JWT_SECRET, MASTER_KEY, TREASURY_ADDRESS, and optional DATABASE_URL
docker compose up --build
```

- Web: http://localhost:8080
- API: http://localhost:8787

The compose file runs the API with a persistent volume (`lm-data`) and the web app behind nginx. To use PostgreSQL, uncomment the `db` service and set `DATABASE_URL`. See [ARCHITECTURE.md](ARCHITECTURE.md) and [SECURITY.md](SECURITY.md).

## Payments — honest version

- The product is **7 days free**, then **$19 / 30 days**.
- Payment is a plain SOL transfer to the project treasury on **Solana mainnet-beta**, approved in the user's wallet.
- The browser builds the transfer, the wallet signs it, then the server independently verifies the transaction (`getTransaction`) for recipient, amount and sender before activating the subscription. Client claims are never trusted.
- The treasury address is configuration, not UI. It is never rendered in the product.
- **Static demo vs. enforcement:** the GitHub Pages build activates the subscription locally to demonstrate the flow; it is not a payment boundary. Only the API verifies the transaction on-chain before activation.
- **Not implemented yet:** fully automatic on-chain recurring billing through the Solana Subscriptions program. Current activation is per period; renewal is a new verified payment. This is stated plainly instead of pretending otherwise.

## Security model

Security is layered, and the limits are stated instead of hidden.

**Client (web)**
- The entire memory snapshot is encrypted at rest with AES-256-GCM using a non-extractable `CryptoKey`. Raw IndexedDB no longer contains readable memories; legacy plaintext snapshots migrate automatically.
- A strict Content-Security-Policy is injected into the production HTML: no `unsafe-eval`, no inline scripts, no third-party JavaScript. Only Google Identity Services is allowed, for sign-in.
- The Google Fonts stylesheet and all other third-party assets were removed; the UI uses the system font stack and works offline. Google Sign-In may load its own button font from Google.
- No `dangerouslySetInnerHTML`, `innerHTML`, `eval` or `new Function` in application code; `npm run security:check` fails CI if one appears or if the CSP weakens.
- LLM keys and vault files are encrypted with the same non-extractable key.

**Server**
- Helmet security headers, per-route rate limits (auth/payment), 1 MB body limit and request timeouts.
- Single-use nonces with an atomic claim, ed25519 signature verification, HMAC JWTs, and production startup refuses to run without `JWT_SECRET` and `MASTER_KEY`.
- Explicit CORS allowlist in production (`CORS_ORIGINS`); ownership checks on every agent route.
- Payments are verified on-chain, priced at the live SOL rate with tolerance, and each signature can activate only one account.
- The server memory snapshot is AES-256-GCM encrypted with `MASTER_KEY` before it reaches SQLite/PostgreSQL; legacy rows migrate on load.

**Honest limits — read this**
- No browser app can fully protect against **active XSS** or a **malicious extension** running in the same origin. A non-extractable key cannot be exported, but injected code can call the app's own decrypt functions while the page is open. Encryption protects data at rest (stolen disk/backup, casual inspection), not a compromised live session.
- Anyone with **physical access** and an unlocked browser profile can read the decrypted session. Use full-disk encryption, a separate browser profile, and lock your device.
- **GitHub Pages cannot send custom HTTP headers.** The meta CSP covers script execution there, but `frame-ancestors`/HSTS/COOP require a real server. The included nginx image sets the full set; use it (or Cloudflare) for a hardened deployment.
- Wallet extensions inject provider scripts by design; only install reputable wallets and keep them updated.

See [SECURITY.md](SECURITY.md) for the full threat model and deployment checklist.

## Repository layout

```
apps/web            React SPA (local-first, static-deployable)
apps/api            Fastify API, SQLite/Postgres, MCP
packages/memory-engine   retention, recall, reflection, maintenance
packages/solana-gate     plan, access states, on-chain payment verification
packages/llm-adapters    OpenAI/Anthropic/Google/local/simulated adapters
packages/shared-types    shared domain types
```

## Development

```bash
npm run typecheck
npm test             # memory engine + encrypted persistence
npm run test:solana  # payment gate
npm run build
npm run security:check  # DOM sinks, cleartext URLs, production CSP
```

Contributions are welcome — see [CONTRIBUTING.md](CONTRIBUTING.md).

## License

MIT © Living Memory contributors. See [LICENSE](LICENSE).

---

## بالعربية

**الذاكرة الحية** طبقة ذاكرة دائمة للوكلاء الأذكياء. يتذكر الوكيل الحقائق والقرارات والتفضيلات، يتأمل تجاربه ليستخلص معرفة دائمة، ويستأنف العمل من حيث توقف بدل أن يبدأ من الصفر.

- **جرّب الآن:** https://pawloblock-byte.github.io/living-memory/ — يعمل داخل المتصفح بذاكرة محلية، دون مفتاح API.
- **التثبيت:** `npm install && npm run dev`، أو `docker compose up --build` للاستضافة الذاتية.
- **الخصوصية:** كل شيء محلي أولًا. مفاتيح النماذج مشفّرة AES-256-GCM، ويمكن تصدير الذاكرة كاملة بصيغة JSON.
- **الاشتراك:** تجربة 7 أيام ثم 19 دولارًا كل 30 يومًا، تُدفع على شبكة Solana الرئيسية ويتم التحقق منها على السلسلة قبل التفعيل. لا يظهر عنوان الخزينة في الواجهة إطلاقًا.
- **الترخيص:** MIT.

اقرأ [ARCHITECTURE.md](ARCHITECTURE.md) لفهم المحرك، و[SECURITY.md](SECURITY.md) لنموذج الأمان.