# https://github.com/memorycrystal/memorycrystal Project Manual

Generated at: 2026-06-25 17:31:01 UTC

## Table of Contents

- [System Architecture & Memory Model](#page-1)
- [Integrations & Host Plugins](#page-2)
- [Backend, Knowledge Bases & Security](#page-3)
- [Operations, Deployment & Diagnostics](#page-4)

<a id='page-1'></a>

## System Architecture & Memory Model

### Related Pages

Related topics: [Integrations & Host Plugins](#page-2), [Backend, Knowledge Bases & Security](#page-3)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md)
- [plugin/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/README.md)
- [plugin/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/package.json)
- [mcp-server/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/README.md)
- [mcp-server/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/package.json)
- [mcp-server/src/lib/convexClient.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/lib/convexClient.ts)
- [package.json](https://github.com/memorycrystal/memorycrystal/blob/main/package.json)
</details>

# System Architecture & Memory Model

Memory Crystal is a persistent-memory substrate for AI agents, exposed both as an Open
Error with Openai API: peer closed connection without sending complete message body (incomplete chunked read)

Please check that you have set the OPENAI_API_KEY environment variable with a valid API key.

---

<a id='page-2'></a>

## Integrations & Host Plugins

### Related Pages

Related topics: [System Architecture & Memory Model](#page-1), [Operations, Deployment & Diagnostics](#page-4)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [plugin/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/README.md)
- [plugin/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/package.json)
- [plugin/store/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/store/package.json)
- [plugin/compaction/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/compaction/package.json)
- [plugin/tools/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/tools/package.json)
- [plugins/shared/crystal-hooks.mjs](https://github.com/memorycrystal/memorycrystal/blob/main/plugins/shared/crystal-hooks.mjs)
- [mcp-server/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/README.md)
- [mcp-server/src/index.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/index.ts)
- [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md)
- [package.json](https://github.com/memorycrystal/memorycrystal/blob/main/package.json)
</details>

# Integrations & Host Plugins

Memory Crystal ships as a layered integration surface: a native **OpenClaw plugin** for deep lifecycle hooks, a **shared hook script** reused by Claude Code / Codex / Factory, and an **MCP server** that exposes the same 24 memory tools to any MCP-compatible host. Together these paths let a single Memory Crystal backend serve OpenClaw conversations, CLI agents, desktop clients, and custom hosts without modifying call sites.

Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md)

## High-Level Integration Architecture

Memory Crystal's repository is structured so each integration variant owns a narrow adapter while sharing the same Convex-backed memory functions.

```
memorycrystal/
├── plugin/                 OpenClaw plugin — hooks into conversation lifecycle
├── plugins/shared/         Shared hook script for Claude Code, Codex, Factory
├── mcp-server/             MCP server — stdio/HTTP compatibility layer
├── packages/mcp-server/    Streamable HTTP MCP variant
└── convex/crystal/         All Memory Crystal Convex functions (shared backend)
```

The OpenClaw plugin imports local modules declared as ESM packages — see the explicit `"type": "module"` markers in [plugin/store/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/store/package.json), [plugin/compaction/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/compaction/package.json), and [plugin/tools/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/tools/package.json).

```mermaid
flowchart LR
  subgraph Hosts
    OC[OpenClaw Plugin]
    CC[Claude Code]
    CX[Codex CLI]
    FD[Factory Droid]
    CD[Claude Desktop]
    H[Hermes Agent]
  end
  OC -->|registerTool / hook events| MCP[MCP Server + HTTP API]
  CC -->|shared hook script| MCP
  CX -->|shared hook script| MCP
  FD -->|shared hook script| MCP
  CD -->|MCP over stdio| MCP
  H -->|register_memory_provider / lifecycle hooks| MCP
  MCP --> CVX[convex/crystal functions]
  CVX --> LTM[(Long-Term Memory + KBs)]
```

Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md)

## OpenClaw Plugin

### Package Layout

The plugin is published as `@memorycrystal/crystal-memory` and ships as a single OpenClaw extension entry point. The manifest wires the extension and narrows the published files to runtime essentials:

```json
{
  "name": "@memorycrystal/crystal-memory",
  "version": "0.8.15",
  "main": "index.js",
  "openclaw": {
    "extensions": ["./index.js"]
  },
  "optionalDependencies": {
    "better-sqlite3": "^12.8.0"
  }
}
```

The `optionalDependencies` declaration keeps `better-sqlite3` lazy so the plugin still loads on hosts where a native build is unavailable. Source: [plugin/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/package.json)

### Lifecycle Hooks

The plugin registers for OpenClaw lifecycle events that together form a complete conversation loop:

| Hook | Responsibility |
|---|---|
| `before_agent_start` | Inject compact memory context, first-turn wake, session-scoped tool guidance |
| `before_tool_call` | Surface action-trigger warnings before risky tools |
| `before_dispatch` | Rate limiting, proactive recall, reinforcement injection |
| `message_received` | Capture incoming user messages |
| `llm_output` | Capture assistant responses and extract durable memories |
| `message_sending` / `message_sent` | Pre/post-send assistant capture fallback for gateway builds lacking model-output callbacks |
| `session_end` | Clear per-session state |
| `before_compaction` / `after_compaction` | Snapshot checkpoint before turns are condensed; refresh local summary state after |

It also watches `/new` and `/reset` command flows to trigger reflection behavior. Source: [plugin/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/README.md)

### Tools Registered via `api.registerTool()`

`plugin/index.js` registers tools that are usable from any OpenClaw session. The full list spans long-term memory recall, knowledge base management, conversation search, and reflection:

- `crystal_recall`, `crystal_remember`, `crystal_what_do_i_know`, `crystal_why_did_we`, `crystal_preflight`
- `crystal_search_messages`, `crystal_checkpoint`, `crystal_wake`, `crystal_trace`
- `crystal_who_owns`, `crystal_explain_connection`, `crystal_dependency_chain`, `crystal_recent`
- `crystal_edit`, `crystal_forget`, `crystal_stats`, `crystal_set_scope`
- `crystal_list_knowledge_bases`, `crystal_query_knowledge_base`, `crystal_import_knowledge`
- `crystal_ideas`, `crystal_idea_action`
- `memory_search`, `memory_get` — legacy compatibility paths returning `crystal/<id>.md`

When the local SQLite-backed store is available, the plugin lazily registers `crystal_grep`, `crystal_describe`, and `crystal_expand` for in-session local history and summaries. Source: [plugin/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/README.md)

## MCP Server Integrations

The MCP server is the universal adapter for non-OpenClaw hosts. It runs in `stdio` mode by default and is launched with the `crystal-mcp` binary.

### Host Configuration Examples

Each supported host gets a one-liner installer or a small MCP config snippet. The same environment variables — `CRYSTAL_MCP_MODE`, `MEMORY_CRYSTAL_API_KEY`, `MEMORY_CRYSTAL_API_URL` — drive every host.

```json
{
  "mcpServers": {
    "memory-crystal": {
      "command": "crystal-mcp",
      "env": {
        "CRYSTAL_MCP_MODE": "stdio",
        "MEMORY_CRYSTAL_API_KEY": "your-api-key-here",
        "MEMORY_CRYSTAL_API_URL": "https://convex.memorycrystal.ai"
      }
    }
  }
}
```

For Codex CLI the server is added via `codex mcp add memory-crystal -- crystal-mcp`, then the env vars are set inline or in shell. Source: [mcp-server/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/README.md)

### Bearer Auth and Convex Client

The MCP server wraps a Convex HTTP client behind a bearer-token middleware. Errors are sanitized so API keys never leak into logs, and tool-error responses have their text redacted before being returned to the host:

```ts
export const sanitizeErrorForLog = (err: unknown): string => {
  const raw = err instanceof Error ? err.message : String(err);
  return redactSecrets(raw);
};

export function redactToolErrorResult(result: CallToolResult): CallToolResult {
  if (!result.isError) return result;
  return {
    ...result,
    content: result.content.map((item) =>
      item.type === "text" && typeof item.text === "string"
        ? { ...item, text: redactSecrets(item.text) }
        : item,
    ),
  };
}
```

The server also enforces a legacy key upgrade message: `CRYSTAL_API_KEY` is rejected with explicit guidance to set `MEMORY_CRYSTAL_API_KEY`. Source: [mcp-server/src/index.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/index.ts)

## Shared Hook Script

Hosts without first-class plugin support — Claude Code, Codex CLI, and Factory Droid — share a single hook script at `plugins/shared/crystal-hooks.mjs`. It is staged by the universal installer during `npm install` or via the platform-specific curl scripts, and it translates host lifecycle events into the same recall / capture / wake calls the OpenClaw plugin uses internally. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md), [mcp-server/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/README.md)

## Knowledge Base Integration Across Hosts

Knowledge bases flow through the same MCP and HTTP surfaces regardless of host, so KB management is consistent whether you reach Memory Crystal via the OpenClaw plugin or an external MCP client:

```
POST /api/knowledge-bases          Create a knowledge base
POST /api/knowledge-bases/:id/import       Import chunks
POST /api/knowledge-bases/:id/bulk-insert  High-volume migration
POST /api/knowledge-bases/:id/query        Query a knowledge base
```

Plugin recall can combine durable conversational memory with scoped KB-backed reference material, while KB scopes respect the same tenant and channel boundaries as the rest of Memory Crystal. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md)

## Operational Notes for Integrators

- **Versioning** — The plugin (`plugin/package.json`) and root lockstep at `v0.8.15`. Source: [plugin/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/package.json)
- **Node engine** — `>=22.13.0` is enforced at the root for self-hosted and local stacks. Source: [package.json](https://github.com/memorycrystal/memorycrystal/blob/main/package.json)
- **Secret hygiene** — Short-term message tools (`crystal_search_messages`, `crystal_recent`, recall message matches, wake/session summaries) redact likely secrets before returning output. A turn becomes searchable only after capture finishes at turn completion; same-turn tool calls cannot expect the current prompt to appear yet. Source: [mcp-server/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/README.md)
- **Hermes integration** — When the Hermes Agent runtime exposes `register_memory_provider`, Memory Crystal registers as a native provider; otherwise it falls back to lifecycle-hook integration. A contract at `integrations/hermes/crystal-memory/CONTRACT.md` pins the surface. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md) (release notes for v0.8.5)

## See Also

- Memory Crystal README — [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md)
- Plugin reference — [plugin/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/README.md)
- MCP server reference — [mcp-server/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/README.md)
- Release notes (v0.8.5..v0.8.15) — [GitHub Releases](https://github.com/memorycrystal/memorycrystal/releases)

---

<a id='page-3'></a>

## Backend, Knowledge Bases & Security

### Related Pages

Related topics: [System Architecture & Memory Model](#page-1), [Operations, Deployment & Diagnostics](#page-4)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md)
- [plugin/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/README.md)
- [plugin/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/package.json)
- [mcp-server/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/README.md)
- [mcp-server/src/index.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/index.ts)
- [mcp-server/src/tools/list-knowledge-bases.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/tools/list-knowledge-bases.ts)
- [mcp-server/src/tools/import-knowledge.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/tools/import-knowledge.ts)
- [mcp-server/src/tools/ideas.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/tools/ideas.ts)
- [package.json](https://github.com/memorycrystal/memorycrystal/blob/main/package.json)
</details>

# Backend, Knowledge Bases & Security

## Overview

Memory Crystal is a Convex-backed persistent memory layer for AI agents. The repository contains the open-source mirror of the system, organized into an OpenClaw plugin (`plugin/`), shared lifecycle hooks (`plugins/shared/`), an MCP server (`mcp-server/`), and Convex functions. The backend exposes both MCP tools (24+) and HTTP endpoints, all guarded by bearer-token authentication. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md).

## Backend Architecture

The runtime stack is built around a Convex deployment plus an MCP/HTTP server. The MCP server in `mcp-server/src/index.ts` performs bearer authentication before any tool invocation and forwards authorized requests to Convex via `ConvexHttpClient`. Source: [mcp-server/src/index.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/index.ts).

```mermaid
flowchart LR
    A[OpenClaw Plugin] -->|hooks| B[MCP Server]
    C[HTTP Client] -->|Bearer token| B
    B -->|verifyBearer| D[Auth Middleware]
    D -->|authorized| E[Convex Functions]
    E --> F[(Convex DB + Storage)]
    E --> G[Embeddings - Gemini]
    E --> H[Organic - OpenRouter]
```

Self-hosted deployments use `npx convex deploy` with a project-level `CONVEX_DEPLOYMENT`, then read `CONVEX_URL` and `GEMINI_API_KEY` from `mcp-server/.env`. Local development uses ports `3210` (Convex RPC), `3211` (HTTP actions), and `6791` (dashboard). Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md). The node engine is pinned to `>=22.13.0` and the package ships vitest, Playwright, and a chaos test config for backend reliability work. Source: [package.json](https://github.com/memorycrystal/memorycrystal/blob/main/package.json).

## Knowledge Bases

Knowledge bases are first-class, immutable reference collections that sit alongside conversational memory. They are tenant- and channel-scoped, support bulk import, and run background enrichment for embeddings and graph backfill. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md).

### Tool surface

| Tool | Purpose |
|---|---|
| `crystal_create_knowledge_base` | Create a curated KB |
| `crystal_list_knowledge_bases` | List KBs, optionally including inactive ones |
| `crystal_import_knowledge` | Import text chunks (title, sourceUrl, chunkIndex, totalChunks) |
| `crystal_query_knowledge_base` | Search inside a specific KB |
| `POST /api/knowledge-bases/:id/bulk-insert` | High-volume migration without blocking on embedding |

Source: [mcp-server/src/tools/list-knowledge-bases.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/tools/list-knowledge-bases.ts), [mcp-server/src/tools/import-knowledge.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/tools/import-knowledge.ts), [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md).

### Recent reliability fixes

- **v0.8.15** de-duplicates byte-identical memories in `/api/mcp/recall` before applying the result limit, and collapses near-duplicate source chunks that share a specific title and identical long content prefix. This stops migration-cloned copies from crowding out distinct results. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md) (release notes).
- **v0.8.14** restores shared training KB results for peer-scoped coach sessions by authorizing content by the caller's agent id rather than treating peer channels as hard content filters. `/api/mcp/recall` now honors both singular `knowledgeBase` and array forms. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md) (release notes).

## Security & Access Control

The security posture combines multi-tenant isolation, bearer-token middleware, secret redaction, and content scanning. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md).

- **Bearer auth** — `extractBearer` and `verifyBearer` in `mcp-server/src/index.ts` gate every tool call before forwarding to Convex. The legacy `CRYSTAL_API_KEY` is rejected with an explicit upgrade message. Source: [mcp-server/src/index.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/index.ts).
- **Secret redaction** — `redactSecrets` is applied to error messages before they are logged (`sanitizeErrorForLog`) and to MCP tool error payloads (`redactToolErrorResult`). Short-term message tools (`crystal_recent`, `crystal_search_messages`, recall message matches, wake/session summaries) redact likely secrets before returning output. Source: [mcp-server/src/index.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/index.ts), [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md).
- **API key storage** — keys are SHA-256 hashed at rest; plaintext is never stored. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md).
- **Per-key rate limiting** — enforced on every authenticated endpoint. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md).
- **Channel capture hardening (v0.8.11)** — unidentified direct sessions fail closed instead of writing private traffic to shared memory; live provider-peer direct session keys (e.g. `telegram:<peerId>`) are accepted only when the hook context matches an explicit peer policy. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md) (release notes).
- **Cost containment (v0.8.7)** — runtime Convex cost-breaker ledger with per-user and global emergency thresholds for recall, message search, and knowledge-base search surfaces. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md) (release notes).

## Community-Noted Security Concerns

The most engaged community issue, **#4 — "Security: Access Control Bypass via MANAGEMENT_CHANNEL_SENTINEL"**, reports that supplying `channel: '__management__'` in `crystal_recall` bypasses knowledge-base visibility restrictions, allowing regular users to read management-level KB data. The recommended mitigation is to validate the caller's role before honoring the sentinel. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md) (community issue link).

Related hardening visible across recent releases reinforces the same theme: prompt-echo sanitization in compact recall evidence (v0.8.13), peer-scoped KB authorization (v0.8.14), and channel capture fail-closed behavior (v0.8.11). Together these narrow the trust assumptions placed on client-supplied channel identifiers. Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md) (release notes).

## See Also

- [Plugin & Hooks](README.md) — OpenClaw plugin lifecycle and tool registry
- [MCP Tools Reference](mcp-server/README.md) — Full
Error with Openai API: peer closed connection without sending complete message body (incomplete chunked read)

Please check that you have set the OPENAI_API_KEY environment variable with a valid API key.

---

<a id='page-4'></a>

## Operations, Deployment & Diagnostics

### Related Pages

Related topics: [Integrations & Host Plugins](#page-2), [Backend, Knowledge Bases & Security](#page-3)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [package.json](https://github.com/memorycrystal/memorycrystal/blob/main/package.json)
- [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md)
- [plugin/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/README.md)
- [plugin/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/package.json)
- [mcp-server/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/README.md)
- [mcp-server/src/index.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/index.ts)
- [mcp-server/src/tools/ideas.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/tools/ideas.ts)
- [mcp-server/src/tools/list-knowledge-bases.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/tools/list-knowledge-bases.ts)
- [mcp-server/src/tools/import-knowledge.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/tools/import-knowledge.ts)
</details>

# Operations, Deployment & Diagnostics

This page covers how Memory Crystal is deployed, operated, and diagnosed in production. It summarizes the three supported deployment modes (Cloud, Self-Hosted, Local-First), the operation scripts bundled in the repository, the `crystal_doctor` diagnostic surface, the runtime cost-breaker ledger, and the configuration knobs operators most frequently touch. It also highlights known security and reliability constraints surfaced by recent releases and community reports.

## Deployment Modes

Memory Crystal supports three deployment targets, all backed by the same Convex backend and the same `@memorycrystal/crystal-memory` OpenClaw plugin (Source: [plugin/package.json](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/package.json)). The README documents each path with its own endpoint set and bootstrap steps.

| Mode | Backend | Endpoints | Bootstrap |
|---|---|---|---|
| Cloud | Hosted Convex | `https://memorycrystal.ai` | Signed-in onboarding; cloud-only routes |
| Self-Hosted | Operator-owned Convex project | `https://<deployment>.convex.cloud` | `convex deploy` + `mcp-server/.env` |
| Local-First | Local Convex backend | `http://127.0.0.1:3210` (RPC), `http://127.0.0.1:3211` (HTTP), `http://127.0.0.1:6791` (dashboard) | `scripts/convex-local-up.sh` + `web:backend:local` |

The Cloud path is gated separately from self-hosted builds so hosted SaaS flows stay isolated (Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md)). The `npm run crystal:enable` and `npm run crystal:doctor` scripts are the canonical verification commands after a fresh install, and OpenClaw plugin installs can be verified with `openclaw plugins info crystal-memory` followed by `openclaw crystal_status`.

### Local-First Stack

The local-first setup runs Convex on three loopback ports and is driven by `scripts/convex-local-up.sh` plus `scripts/convex-local-write-env.ts`. The `package.json` exposes helper targets:

- `web:backend:local` → writes the local Convex env (Source: [package.json](https://github.com/memorycrystal/memorycrystal/blob/main/package.json))
- `package:local-backend` → bundles the local backend for distribution (Source: [package.json](https://github.com/memorycrystal/memorycrystal/blob/main/package.json))
- `test:local` → executes `test-local.sh` against the local stack (Source: [package.json](https://github.com/memorycrystal/memorycrystal/blob/main/package.json))

The `mcp-server` README documents the same port assignments and recommends the `docs.memorycrystal.ai/configuration/local-first` guide for backup, rollback, and troubleshooting (Source: [mcp-server/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/README.md)).

### Hermes Agent Integration

For Hermes installations, Memory Crystal registers as a native memory provider when Hermes exposes `register_memory_provider` and falls back to lifecycle hooks for older Hermes runtimes. The integration ships a `CONTRACT.md` so operators can verify expected behavior end-to-end (added in v0.8.5).

## Diagnostics & Health Checks

The primary operator-facing diagnostic tool is `crystal_doctor`. It began as a Hermes-only surface in v0.8.8 and was extended in v0.8.12 to report a richer hook-state summary across installations.

### crystal_doctor Output

`crystal_doctor` reports (v0.8.12+):

- **Hook registration API** — which registration entrypoint the plugin used (e.g., `register_memory_provider` vs. lifecycle hooks).
- **Registered hook names** — the exact set of OpenClaw hooks the plugin bound (e.g., `before_agent_start`, `before_dispatch`, `message_received`, `llm_output`, `session_end`).
- **Registration time** — when the hooks were bound during the current process lifetime.
- **Last hook event** — the most recent hook that fired.
- **Last resolved session/channel** — the session and channel the last hook event targeted.
- **Last hook skip reason** — why the hook was bypassed, if applicable.

If hooks are registered but no callbacks have fired since plugin load, `crystal_doctor` emits a warning so operators can detect provider disconnects or misconfigurations without parsing raw status JSON (added in v0.8.12).

For Hermes installs, `crystal_doctor` also surfaces backend, mode, queue, tool-surface, and scoping diagnostics in human-readable form (added in v0.8.8).

```mermaid
flowchart LR
  A[Operator runs crystal_doctor] --> B{Hook registered?}
  B -- Yes --> C{Fired since load?}
  C -- No --> W[Warn: no callbacks since plugin load]
  C -- Yes --> D[Report last hook event + session/channel + skip reason]
  B -- No --> E[Report missing registration API + suggested fix]
  D --> F[Report hook names, registration time, mode, queue]
  F --> G[Operator triages]
```

### Live Smoke Coverage

Gated live smoke coverage exercises auth, stats, wake, recall, recent-message, and search paths against a running Hermes install so regressions are caught before release (added in v0.8.8). The Convex equivalent, `scripts/convex-cost-smoke.mjs`, replays production Convex JSONL logs against the cost-breaker ledger to validate threshold behavior (added in v0.8.7).

## Operations Scripts & Cost Containment

The repository bundles a set of operation scripts under `scripts/` and exposes them through `npm run` targets in `package.json`:

- `scripts/convex-local-up.sh` — boots the local Convex backend on ports 3210/3211/6791.
- `scripts/convex-local-write-env.ts` — writes the local Convex URL into `mcp-server/.env`.
- `scripts/convex-local-doctor.sh` — runs local-stack health checks.
- `scripts/web-backend-env.ts` — emits `local` or `remote` web-backend env files.
- `scripts/package-local-backend.mjs` — packages the local backend for distribution.
- `scripts/convex-cost-smoke.mjs` — replays JSONL logs against the cost breaker.
- `test-local.sh` / `test-remote.sh` — full local and remote test runs (Source: [package.json](https://github.com/memorycrystal/memorycrystal/blob/main/package.json)).

The runtime **Convex cost-breaker ledger** (added in v0.8.7) enforces per-user and global emergency thresholds for three surfaces: `recall`, message search, and knowledge-base search. When a threshold trips, the surface returns a degraded result rather than a hard error, allowing operators to keep partial service while the spike is investigated.

## Configuration, Security & Known Issues

Configuration is environment-driven and concentrated in `mcp-server/.env`. Notable keys include `CONVEX_URL`, `MEMORY_CRYSTAL_API_KEY` (the replacement for the deprecated `CRYSTAL_API_KEY` per [mcp-server/src/index.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/index.ts)), `GEMINI_API_KEY` for embeddings, and the optional `OPENROUTER_API_KEY` for organic features (Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md)).

### Authentication Surface

All MCP and HTTP endpoints require `Authorization: Bearer <api-key>`, with per-key rate limiting (Source: [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md)). API keys are SHA-256 hashed at rest and the plaintext is never persisted. The `CRYSTAL_API_KEY is no longer supported` upgrade message in the server bootstrap makes it explicit when older deployments need to rotate to `MEMORY_CRYSTAL_API_KEY` (Source: [mcp-server/src/index.ts](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/src/index.ts)).

### Reported Security Issue

Community issue #4 reports an **access control bypass via the `MANAGEMENT_CHANNEL_SENTINEL`** (`__management__`) in `crystal_recall` requests, which allows regular users to query management-level knowledge base data. The recommendation is to validate roles before honoring the sentinel. Operators running custom front-ends on top of `mcp-server` should verify that any code path accepting a user-supplied channel rejects `__management__` unless the caller is explicitly authorized.

### Channel Capture Hardening

For OpenClaw channels, v0.8.11 introduced stricter direct-session handling: live provider-peer direct session keys (e.g., `telegram:<peerId>`) are accepted only when the hook context matches an explicit peer policy, and unidentified direct sessions are closed instead of writing private traffic to shared memory. The `openclaw-hook.json` install asset was restored and verified as part of that release.

## See Also

- [README.md](https://github.com/memorycrystal/memorycrystal/blob/main/README.md) — high-level overview, mode summaries, and verification commands.
- [plugin/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/plugin/README.md) — OpenClaw hook surface and plugin directory layout.
- [mcp-server/README.md](https://github.com/memorycrystal/memorycrystal/blob/main/mcp-server/README.md) — MCP tool surface, memory stores, and categories.
- [package.json](https://github.com/memorycrystal/memorycrystal/blob/main/package.json) — every npm-script operation target.
- [Memory Crystal releases](https://github.com/memorycrystal/memorycrystal/releases) — per-version change history, including the v0.8.15 recall quality fixes, v0.8.12 doctor upgrades, v0.8.11 channel hardening, and v0.8.7 cost-breaker ledger.

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Pitfall Log

Project: memorycrystal/memorycrystal

Summary: Found 18 structured pitfall item(s), including 0 high/blocking item(s). Top priority: Identity risk - Identity risk requires verification.

## 1. Identity risk - Identity risk requires verification

- Severity: medium
- Evidence strength: runtime_trace
- Finding: Project evidence flags a identity risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Repro command: `npm install @memorycrystal/crystal-memory`
- Evidence: identity.distribution | https://github.com/memorycrystal/memorycrystal

## 2. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Developers should check this installation risk before relying on the project: Memory Crystal v0.8.11
- User impact: Upgrade or migration may change expected behavior: Memory Crystal v0.8.11
- Evidence: failure_mode_cluster:github_release | https://github.com/memorycrystal/memorycrystal/releases/tag/v0.8.11

## 3. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Developers should check this installation risk before relying on the project: Memory Crystal v0.8.12
- User impact: Upgrade or migration may change expected behavior: Memory Crystal v0.8.12
- Evidence: failure_mode_cluster:github_release | https://github.com/memorycrystal/memorycrystal/releases/tag/v0.8.12

## 4. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Developers should check this installation risk before relying on the project: Memory Crystal v0.8.13
- User impact: Upgrade or migration may change expected behavior: Memory Crystal v0.8.13
- Evidence: failure_mode_cluster:github_release | https://github.com/memorycrystal/memorycrystal/releases/tag/v0.8.13

## 5. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Developers should check this installation risk before relying on the project: Memory Crystal v0.8.14
- User impact: Upgrade or migration may change expected behavior: Memory Crystal v0.8.14
- Evidence: failure_mode_cluster:github_release | https://github.com/memorycrystal/memorycrystal/releases/tag/v0.8.14

## 6. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Developers should check this installation risk before relying on the project: Memory Crystal v0.8.4
- User impact: Upgrade or migration may change expected behavior: Memory Crystal v0.8.4
- Evidence: failure_mode_cluster:github_release | https://github.com/memorycrystal/memorycrystal/releases/tag/v0.8.4

## 7. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Developers should check this installation risk before relying on the project: Memory Crystal v0.8.5
- User impact: Upgrade or migration may change expected behavior: Memory Crystal v0.8.5
- Evidence: failure_mode_cluster:github_release | https://github.com/memorycrystal/memorycrystal/releases/tag/v0.8.5

## 8. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Developers should check this installation risk before relying on the project: Memory Crystal v0.8.6
- User impact: Upgrade or migration may change expected behavior: Memory Crystal v0.8.6
- Evidence: failure_mode_cluster:github_release | https://github.com/memorycrystal/memorycrystal/releases/tag/v0.8.6

## 9. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Developers should check this installation risk before relying on the project: Memory Crystal v0.8.7
- User impact: Upgrade or migration may change expected behavior: Memory Crystal v0.8.7
- Evidence: failure_mode_cluster:github_release | https://github.com/memorycrystal/memorycrystal/releases/tag/v0.8.7

## 10. Installation risk - Installation risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Developers should check this installation risk before relying on the project: Memory Crystal v0.8.8
- User impact: Upgrade or migration may change expected behavior: Memory Crystal v0.8.8
- Evidence: failure_mode_cluster:github_release | https://github.com/memorycrystal/memorycrystal/releases/tag/v0.8.8

## 11. Configuration risk - Configuration risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Project evidence flags a configuration risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: capability.host_targets | https://github.com/memorycrystal/memorycrystal

## 12. Capability evidence risk - Capability evidence risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: capability.assumptions | https://github.com/memorycrystal/memorycrystal

## 13. Maintenance risk - Maintenance risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Developers should check this migration risk before relying on the project: Memory Crystal v0.8.15
- User impact: Upgrade or migration may change expected behavior: Memory Crystal v0.8.15
- Evidence: failure_mode_cluster:github_release | https://github.com/memorycrystal/memorycrystal/releases/tag/v0.8.15

## 14. Maintenance risk - Maintenance risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: Project evidence flags a maintenance risk. Review the linked source before relying on this workflow.
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: evidence.maintainer_signals | https://github.com/memorycrystal/memorycrystal

## 15. Security or permission risk - Security or permission risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: downstream_validation.risk_items | https://github.com/memorycrystal/memorycrystal

## 16. Security or permission risk - Security or permission risk requires verification

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: risks.scoring_risks | https://github.com/memorycrystal/memorycrystal

## 17. Maintenance risk - Maintenance risk requires verification

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: evidence.maintainer_signals | https://github.com/memorycrystal/memorycrystal

## 18. Maintenance risk - Maintenance risk requires verification

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: May increase setup, validation, or first-run risk for the user.
- Evidence: evidence.maintainer_signals | https://github.com/memorycrystal/memorycrystal

<!-- canonical_name: memorycrystal/memorycrystal; human_manual_source: deepwiki_human_wiki -->
