# https://github.com/thedotmack/claude-mem 项目说明书

生成时间：2026-05-15 12:40:04 UTC

## 目录

- [Introduction to Claude-Mem](#page-introduction)
- [Key Features](#page-key-features)
- [System Architecture Overview](#page-architecture-overview)
- [Hooks System and Lifecycle](#page-hooks-system)
- [Worker Service Architecture](#page-worker-service)
- [Database Schema and Storage](#page-database-schema)
- [Data Flow and Processing](#page-data-flow)
- [Search Architecture](#page-search-architecture)
- [MCP Tools and Context Generation](#page-mcp-tools)
- [Installation Guide](#page-installation)

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

## Introduction to Claude-Mem

### 相关页面

相关主题：[Key Features](#page-key-features), [System Architecture Overview](#page-architecture-overview)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/thedotmack/claude-mem/blob/main/README.md)
- [src/sdk/prompts.ts](https://github.com/thedotmack/claude-mem/blob/main/src/sdk/prompts.ts)
- [src/ui/viewer/components/SummaryCard.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/SummaryCard.tsx)
- [src/ui/viewer/components/ObservationCard.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/ObservationCard.tsx)
- [src/ui/viewer/components/ContextSettingsModal.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/ContextSettingsModal.tsx)
- [src/server/generation/providers/shared/prompt-builder.ts](https://github.com/thedotmack/claude-mem/blob/main/src/server/generation/providers/shared/prompt-builder.ts)
- [src/npx-cli/commands/install.ts](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/commands/install.ts)
</details>

# Introduction to Claude-Mem

Claude-Mem is a persistent memory plugin for Claude Code that automatically captures tool usage observations, generates semantic summaries, and makes them available across sessions. It enables Claude to maintain continuity of knowledge about projects even after sessions end or reconnect.

资料来源：[README.md:1]()

## Overview

Claude-Mem solves the context continuity problem in AI-assisted development by:

- **Automatically capturing** tool usage observations during development sessions
- **Generating semantic summaries** using configurable AI models
- **Persisting memory** in a local SQLite database (`~/.claude-mem`)
- **Injecting relevant context** into new Claude Code sessions automatically

The system operates as a background worker service that monitors Claude Code activity, processes observations through AI models, and serves memory context on demand.

资料来源：[README.md:1]()

## Architecture

### System Components

Claude-Mem consists of several interconnected components:

| Component | Location | Purpose |
|-----------|----------|---------|
| **NPX CLI** | `src/npx-cli/` | Installation, startup, and management commands |
| **Worker Service** | `src/server/` | Background service for observation processing |
| **SDK** | `src/sdk/` | Prompt building and shared utilities |
| **UI Viewer** | `src/ui/viewer/` | Web-based memory viewer interface |
| **Smart File Reader** | `src/services/smart-file-read/` | Intelligent code parsing and symbol extraction |

资料来源：[src/npx-cli/commands/install.ts:1]()

### Data Flow

```mermaid
graph TD
    A[Claude Code Session] -->|Tool Usage Events| B[Claude-Mem Hooks]
    B -->|Observation Data| C[Worker Service]
    C -->|API Request| D[AI Provider<br/>Claude/Gemini]
    D -->|Structured Observation| E[SQLite Database<br/>~/.claude-mem]
    E -->|Context Injection| F[Next Claude Session]
    
    G[UI Viewer] <-->|Query/Display| E
    G -->|Settings Changes| C
```

资料来源：[src/server/generation/providers/shared/prompt-builder.ts:1]()

### Plugin Modes

Claude-Mem supports different observation modes through the `ModeConfig` system. Each mode defines:

- Prompt templates for observation generation
- Observation types (e.g., `code_change`, `investigation`, `learning`)
- XML output schema for structured responses
- Mode-specific field guidance

资料来源：[src/sdk/prompts.ts:1]()

## Installation

### Standard Installation (Claude Code)

```bash
npx claude-mem install
```

资料来源：[README.md:11]()

### Gemini CLI Installation

```bash
npx claude-mem install --ide gemini-cli
```

资料来源：[README.md:14]()

### OpenCode Installation

```bash
npx claude-mem install --ide opencode
```

资料来源：[README.md:17]()

### Claude Code Plugin Marketplace

```bash
/plugin marketplace add thedotmack/claude-mem
/plugin install claude-mem
```

资料来源：[README.md:20]()

> **Note:** The npm package (`npm install -g claude-mem`) installs only the SDK/library—it does not register plugin hooks or set up the worker service. Always use `npx claude-mem install` or the `/plugin` commands.

资料来源：[README.md:27]()

## Configuration Options

The memory context can be configured through environment variables or the UI settings modal:

| Setting | Default | Description |
|---------|---------|-------------|
| `CLAUDE_MEM_CONTEXT_OBSERVATIONS` | 50 | Number of recent observations to include (1-200) |
| `CLAUDE_MEM_CONTEXT_SESSIONS` | 10 | Number of recent sessions to pull from (1-50) |
| `CLAUDE_MEM_PROVIDER` | claude | AI provider: `claude` or `gemini` |
| `CLAUDE_MEM_MODEL` | haiku | Claude model: `haiku`, `sonnet`, or `opus` |
| `CLAUDE_MEM_GEMINI_MODEL` | gemini-2.5-flash-lite | Gemini model variant |

资料来源：[src/ui/viewer/components/ContextSettingsModal.tsx:1]()

## Data Models

### Observation Structure

Observations are the core data unit in Claude-Mem:

```typescript
interface Observation {
  id: string;
  tool_name: string;
  tool_input: string | object;
  tool_output: string | object;
  type: string;           // Observation type (e.g., "code_change")
  title: string;
  subtitle?: string;
  facts: string[];
  narrative?: string;
  concepts: string[];
  files_read: string[];
  files_modified: string[];
  project: string;
  created_at_epoch: number;
}
```

资料来源：[src/sdk/prompts.ts:1]()

### Summary Structure

Session summaries provide high-level context:

```typescript
interface Summary {
  id: string;
  request: string;        // What was requested
  investigated: string;   // What was explored
  learned: string;        // Key findings
  completed: string;      // What was accomplished
  next_steps: string;     // Suggested follow-ups
  notes?: string;         // Additional notes
  project: string;
  created_at_epoch: number;
}
```

资料来源：[src/ui/viewer/components/SummaryCard.tsx:1]()

## Observation Generation

### Prompt Building System

The SDK (`src/sdk/prompts.ts`) provides functions to construct structured prompts:

| Function | Purpose |
|----------|---------|
| `buildFirstObservationPrompt()` | Initial observation for new sessions |
| `buildContinuationPrompt()` | Continue observation from existing context |
| `buildSummaryPrompt()` | Generate session summary |
| `buildObservationPrompt()` | Process individual tool observations |

资料来源：[src/sdk/prompts.ts:1]()

### XML Output Schema

Observations are formatted using XML with the following structure:

```xml
<observation>
  <type>[ code_change | investigation | learning | error_fix ]</type>
  <title>Brief descriptive title</title>
  <subtitle>Optional context summary</subtitle>
  <facts>
    <fact>Key fact 1</fact>
    <fact>Key fact 2</fact>
  </facts>
  <narrative>Descriptive narrative of the action</narrative>
  <concepts>
    <concept>Technical concept 1</concept>
  </concepts>
  <files_read>
    <file>path/to/file.ts</file>
  </files_read>
  <files_modified>
    <file>path/to/modified.ts</file>
  </files_modified>
</observation>
```

资料来源：[src/server/generation/providers/shared/prompt-builder.ts:1]()

### XML Escaping

The prompt builder includes proper XML escaping to prevent injection:

```typescript
function escapeXml(text: string): string {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}
```

资料来源：[src/server/generation/providers/shared/prompt-builder.ts:1]()

## User Interface

### Viewer Components

The web-based UI viewer provides several key components:

| Component | File | Description |
|-----------|------|-------------|
| `Header` | `Header.tsx` | Navigation bar with logo, status, and links |
| `WelcomeCard` | `WelcomeCard.tsx` | First-time user onboarding modal |
| `SummaryCard` | `SummaryCard.tsx` | Display session summaries with sections |
| `ObservationCard` | `ObservationCard.tsx` | Display individual observations with toggle views |
| `ContextSettingsModal` | `ContextSettingsModal.tsx` | Configuration panel with live preview |
| `LogsModal` | `LogsModal.tsx` | Real-time worker log viewer |

资料来源：[src/ui/viewer/components/Header.tsx:1]()
资料来源：[src/ui/viewer/components/WelcomeCard.tsx:1]()
资料来源：[src/ui/viewer/components/SummaryCard.tsx:1]()

### Theme System

The viewer supports light and dark themes via CSS custom properties:

```css
:root, [data-theme="light"] {
  --color-bg-primary: #ffffff;
  --color-bg-secondary: #efebe4;
  --color-bg-button: #0969da;
}

[data-theme="dark"] {
  --color-bg-primary: #0d1117;
  --color-bg-secondary: #161b22;
  --color-bg-button: #238636;
}
```

资料来源：[src/ui/viewer-template.html:1]()

### Observation Card Display Modes

The observation card supports multiple view modes:

1. **Default View**: Shows title and subtitle
2. **Facts View**: Displays bullet-pointed facts with concepts and file references
3. **Narrative View**: Shows the full narrative description

资料来源：[src/ui/viewer/components/ObservationCard.tsx:1]()

## Smart File Reading

The `smart-file-read` service provides intelligent code parsing:

| Feature | Description |
|---------|-------------|
| Symbol extraction | Identifies functions, classes, interfaces, variables |
| Markdown processing | Handles code blocks, frontmatter, and references |
| JSDoc/Python docstring detection | Extracts documentation comments |
| Export tracking | Determines which symbols are exported |
| Duplicate code block detection | Identifies repeated code blocks |

资料来源：[src/services/smart-file-read/parser.ts:1]()

## First-Time Usage

After installation:

1. **Start the worker**: The install command automatically starts the background worker
2. **Open the dashboard**: Navigate to `http://localhost:<port>` to view the memory viewer
3. **Start coding**: Open Claude Code in any project
4. **Observe**: Observations automatically stream in as you work
5. **Context injection**: Memory becomes available in your second session in a project

资料来源：[src/npx-cli/commands/install.ts:1]()

## Troubleshooting

If experiencing issues, Claude Code can automatically diagnose problems:

```bash
cd ~/.claude/plugins/marketplaces/thedotmack
npm run bug-report
```

资料来源：[README.md:57]()

## Development

For development and contribution guidelines, see the [Development Guide](https://docs.claude-mem.ai/development).

## License

Claude-Mem is licensed under the Apache License 2.0, enabling use in developer tools, local agents, MCP servers, enterprise systems, robotics stacks, and production agent harnesses.

资料来源：[README.md:82]()

---

<a id='page-key-features'></a>

## Key Features

### 相关页面

相关主题：[Introduction to Claude-Mem](#page-introduction), [MCP Tools and Context Generation](#page-mcp-tools), [Search Architecture](#page-search-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/thedotmack/claude-mem/blob/main/README.md)
- [src/sdk/prompts.ts](https://github.com/thedotmack/claude-mem/blob/main/src/sdk/prompts.ts)
- [src/server/generation/providers/shared/prompt-builder.ts](https://github.com/thedotmack/claude-mem/blob/main/src/server/generation/providers/shared/prompt-builder.ts)
- [src/ui/viewer/components/SummaryCard.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/SummaryCard.tsx)
- [src/ui/viewer/components/ObservationCard.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/ObservationCard.tsx)
- [src/ui/viewer/components/ContextSettingsModal.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/ContextSettingsModal.tsx)
- [src/ui/viewer/App.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/App.tsx)
- [src/services/smart-file-read/parser.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/smart-file-read/parser.ts)
</details>

# Key Features

Claude-Mem provides persistent memory capabilities for AI coding assistants, enabling continuity of knowledge across sessions. This page documents the core architectural components and features that power the system.

## System Overview

Claude-Mem seamlessly preserves context across sessions by automatically capturing tool usage observations, generating semantic summaries, and making them available to future sessions. This enables Claude to maintain continuity of knowledge about projects even after sessions end or reconnect.

资料来源：[README.md](https://github.com/thedotmack/claude-mem/blob/main/README.md)

## Core Features

### 1. Observation Capture System

The observation system automatically records tool usage events during Claude Code sessions. Each observation captures structured data about file operations, command executions, and code modifications.

#### Observation Data Model

| Field | Type | Description |
|-------|------|-------------|
| `type` | string | Category of observation (file_read, file_modified, command, etc.) |
| `title` | string | Brief title for the observation |
| `subtitle` | string | Additional context or description |
| `facts` | string[] | Key facts extracted from the operation |
| `narrative` | string | Human-readable summary of the activity |
| `concepts` | string[] | Extracted concepts and patterns |
| `files_read` | string[] | Files that were read during this operation |
| `files_modified` | string[] | Files that were modified |
| `id` | number | Unique identifier for the observation |
| `created_at_epoch` | number | Unix timestamp of creation |

资料来源：[src/sdk/prompts.ts:24-42](https://github.com/thedotmack/claude-mem/blob/main/src/sdk/prompts.ts)

#### XML Output Format

Observations are rendered in a structured XML format that the AI can easily parse:

```xml
<observation>
  <type>[ file_read | file_modified | command | code_change ]</type>
  <title>...</title>
  <subtitle>...</subtitle>
  <facts>
    <fact>...</fact>
  </facts>
  <narrative>...</narrative>
  <concepts>
    <concept>...</concept>
  </concepts>
  <files_read>
    <file>...</file>
  </files_read>
  <files_modified>
    <file>...</file>
  </files_modified>
</observation>
```

资料来源：[src/server/generation/providers/shared/prompt-builder.ts:75-89](https://github.com/thedotmack/claude-mem/blob/main/src/server/generation/providers/shared/prompt-builder.ts)

### 2. Semantic Summary Generation

Session summaries provide high-level overviews of completed work. The summary system uses specialized prompts to extract key information from the session context.

#### Summary Data Model

| Field | Description |
|-------|-------------|
| `request` | Original user request or task description |
| `investigated` | Topics researched during the session |
| `learned` | Key findings and discoveries |
| `completed` | Tasks that were successfully completed |
| `next_steps` | Recommended follow-up actions |
| `notes` | Additional relevant notes |
| `project` | Associated project identifier |
| `id` | Unique summary identifier |

资料来源：[src/sdk/prompts.ts:85-96](https://github.com/thedotmack/claude-mem/blob/main/src/sdk/prompts.ts)

#### Summary Output Format

```xml
<summary>
  <request>...</request>
  <investigated>...</investigated>
  <learned>...</learned>
  <completed>...</completed>
  <next_steps>...</next_steps>
  <notes>...</notes>
</summary>
```

资料来源：[src/sdk/prompts.ts:98-110](https://github.com/thedotmack/claude-mem/blob/main/src/sdk/prompts.ts)

### 3. Context Injection

Claude-Mem injects relevant observations into new sessions, allowing Claude to recall previous work on the project.

#### Context Configuration Options

| Setting | Default | Range | Description |
|---------|---------|-------|-------------|
| `CLAUDE_MEM_CONTEXT_OBSERVATIONS` | 50 | 1-200 | Number of recent observations to include |
| `CLAUDE_MEM_CONTEXT_SESSIONS` | - | 1-50 | Number of recent sessions to pull from |

资料来源：[src/ui/viewer/components/ContextSettingsModal.tsx:45-60](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/ContextSettingsModal.tsx)

### 4. Multi-IDE Support

Claude-Mem supports installation across multiple AI coding environments:

| IDE | Installation Command |
|-----|---------------------|
| Claude Code | `npx claude-mem install` |
| Gemini CLI | `npx claude-mem install --ide gemini-cli` |
| OpenCode | `npx claude-mem install --ide opencode` |

资料来源：[README.md](https://github.com/thedotmack/claude-mem/blob/main/README.md)

### 5. Smart File Parsing

The parser extracts meaningful symbols from code files, supporting intelligent code analysis:

```typescript
interface CodeSymbol {
  name: string;
  kind: 'function' | 'class' | 'variable' | 'interface' | 'type' | 'code' | 'metadata' | 'reference';
  signature: string;
  jsdoc?: string;
  lineStart: number;
  lineEnd: number;
  exported: boolean;
  children?: CodeSymbol[];
}
```

Supported languages include JavaScript, TypeScript, Python, Markdown (with code block detection), and more.

资料来源：[src/services/smart-file-read/parser.ts:1-50](https://github.com/thedotmack/claude-mem/blob/main/src/services/smart-file-read/parser.ts)

### 6. Web Viewer Interface

The built-in web viewer provides a graphical interface for browsing past observations and summaries.

#### Viewer Components

| Component | Purpose |
|-----------|---------|
| `SummaryCard` | Displays session summaries with request title, sections, and metadata |
| `ObservationCard` | Shows individual observations with facts, narrative, and file references |
| `ContextSettingsModal` | Configuration panel for context injection settings |
| `WelcomeCard` | First-time user introduction and feature overview |
| `Header` | Navigation and status indicators |
| `LogsModal` | Application logs and debugging information |

资料来源：[src/ui/viewer/App.tsx:1-100](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/App.tsx)

#### Summary Card Display

The UI renders summary sections with animation delays for visual polish:

```typescript
sections.map((section, index) => (
  <section
    key={section.key}
    className="summary-section"
    style={{ animationDelay: `${index * 50}ms` }}
  >
    <div className="summary-section-header">
      <img src={section.icon} alt={section.label} />
      <h3>{section.label}</h3>
    </div>
    <div className="summary-section-content">
      {section.content}
    </div>
  </section>
))
```

资料来源：[src/ui/viewer/components/SummaryCard.tsx:30-50](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/SummaryCard.tsx)

#### Observation Card Display

Observations support multiple view modes for flexible data presentation:

```typescript
{showFacts && facts.length > 0 && (
  <ul className="facts-list">
    {facts.map((fact: string, i: number) => (
      <li key={i}>{fact}</li>
    ))}
  </ul>
)}

{showNarrative && observation.narrative && (
  <div className="narrative">
    {observation.narrative}
  </div>
)}
```

资料来源：[src/ui/viewer/components/ObservationCard.tsx:50-65](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/ObservationCard.tsx)

### 7. Theme System

The viewer supports light and dark themes with CSS custom properties:

| Theme Variable | Light Mode | Dark Mode |
|----------------|------------|-----------|
| `--color-bg-primary` | #ffffff | #0d1117 |
| `--color-bg-secondary` | #efebe4 | #161b22 |
| `--color-bg-card` | #ffffff | #161b22 |
| `--color-bg-button` | #0969da | #238636 |

资料来源：[src/ui/viewer-template.html:20-40](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer-template.html)

## Architecture Diagram

```mermaid
graph TD
    A[Claude Code Session] --> B[Observation Capture]
    B --> C[Worker Service]
    C --> D[SQLite Database]
    D --> E[Context Builder]
    E --> F[Prompt Injection]
    F --> A
    
    C --> G[Summary Generation]
    G --> D
    
    H[Web Viewer] --> E
    H --> D
    
    I[Smart File Parser] --> B
```

## Data Flow

```mermaid
sequenceDiagram
    participant User
    participant Claude as Claude Code
    participant SDK as SDK/prompts.ts
    participant Worker as Worker Service
    participant DB as SQLite
    participant Viewer as Web Viewer
    
    User->>Claude: Start session
    Claude->>SDK: Generate observation
    SDK->>Worker: Send observation data
    Worker->>DB: Store observation
    
    User->>Viewer: Browse observations
    Viewer->>DB: Query observations
    DB-->>Viewer: Return data
    
    User->>Claude: End session
    Claude->>SDK: Request summary
    SDK->>Worker: Generate summary
    Worker->>DB: Store summary
    
    User->>Claude: New session
    Viewer->>Claude: Inject context
    Claude->>User: Respond with context
```

## Key System Behaviors

### Observation Types

The system recognizes several observation types that categorize different tool operations:

1. **file_read** - When Claude reads a file
2. **file_modified** - When Claude edits or creates a file
3. **command** - When Claude runs shell commands
4. **code_change** - When significant code modifications occur

### XML Escaping

All user-generated content is properly escaped before insertion into XML output to prevent injection attacks:

```typescript
function escapeXml(text: string): string {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}
```

资料来源：[src/server/generation/providers/shared/prompt-builder.ts:91-98](https://github.com/thedotmack/claude-mem/blob/main/src/server/generation/providers/shared/prompt-builder.ts)

### Error Handling

The viewer implements error boundaries to gracefully handle component failures:

```typescript
class ErrorBoundary extends React.Component {
  state = { error: null, errorInfo: null };
  
  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    this.setState({ error, errorInfo });
  }
  
  render() {
    if (this.state.error) {
      return (
        <details>
          <summary>Error details</summary>
          <pre>{this.state.error.toString()}</pre>
        </details>
      );
    }
    return this.props.children;
  }
}
```

资料来源：[src/ui/viewer/components/ErrorBoundary.tsx:1-40](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/ErrorBoundary.tsx)

## Installation & Setup

### Quick Install

```bash
# Standard Claude Code
npx claude-mem install

# Gemini CLI
npx claude-mem install --ide gemini-cli

# OpenCode
npx claude-mem install --ide opencode
```

### Post-Installation

1. Keep the viewer URL open in a browser
2. Open Claude Code in any project
3. Observations stream automatically as Claude works
4. Memory injection begins on the second session

资料来源：[src/npx-cli/commands/install.ts:15-30](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/commands/install.ts)

## Storage Location

All data is stored locally in `~/.claude-mem` on the user's machine. No data is sent to external servers except through Claude API calls for observation generation.

## See Also

- [Installation Guide](https://github.com/thedotmack/claude-mem#installation)
- [Context Settings](src/ui/viewer/components/ContextSettingsModal.tsx)
- [Prompt Builder](src/server/generation/providers/shared/prompt-builder.ts)

---

<a id='page-architecture-overview'></a>

## System Architecture Overview

### 相关页面

相关主题：[Hooks System and Lifecycle](#page-hooks-system), [Worker Service Architecture](#page-worker-service), [Database Schema and Storage](#page-database-schema), [Data Flow and Processing](#page-data-flow)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/thedotmack/claude-mem/blob/main/README.md)
- [src/sdk/prompts.ts](https://github.com/thedotmack/claude-mem/blob/main/src/sdk/prompts.ts)
- [src/server/generation/providers/shared/prompt-builder.ts](https://github.com/thedotmack/claude-mem/blob/main/src/server/generation/providers/shared/prompt-builder.ts)
- [src/ui/viewer/App.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/App.tsx)
- [src/ui/viewer/components/ContextSettingsModal.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/ContextSettingsModal.tsx)
- [src/npx-cli/commands/install.ts](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/commands/install.ts)
</details>

# System Architecture Overview

Claude-Mem is a persistent memory system for AI coding assistants (Claude Code, Gemini CLI, OpenCode). It automatically captures tool usage observations during coding sessions, generates semantic summaries, and makes them available to future sessions—enabling continuity of knowledge across sessions. 资料来源：[README.md](https://github.com/thedotmack/claude-mem/blob/main/README.md)

## High-Level Architecture

The system follows a client-server architecture with a worker service that runs independently and a viewer UI for inspecting memory.

```mermaid
graph TD
    A[Claude Code / Gemini CLI] -->|Tool Hooks| B[claude-mem Plugin Hooks]
    B --> C[Worker Service :3000]
    C --> D[(SQLite Database<br/>~/.claude-mem)]
    C --> E[Prompt Builder]
    E --> F[Claude API]
    F --> G[Parsed Observations]
    C --> G
    H[Viewer UI :8080] --> C
    H --> D
```

## Core Components

### 1. Worker Service (`src/services/worker-service.ts`)

The worker service is the central processing hub that:

- Runs as a background process (default port 3000)
- Receives tool usage observations from IDE plugins
- Processes and stores observations in SQLite
- Handles prompt generation and LLM interaction
- Manages session context injection

资料来源：[src/npx-cli/commands/install.ts](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/commands/install.ts)

### 2. SDK Layer (`src/sdk/prompts.ts`)

The SDK provides prompt building functions for different operation modes:

| Function | Purpose |
|----------|---------|
| `buildObservationPrompt()` | Creates prompts for parsing tool observations into structured XML format |
| `buildSummaryPrompt()` | Generates prompts for creating session summaries |
| `buildContinuationPrompt()` | Builds prompts for continuing sessions with existing context |

The SDK uses `ModeConfig` objects that define observation types, prompt templates, and output format guidelines specific to each IDE integration.

资料来源：[src/sdk/prompts.ts](https://github.com/thedotmack/claude-mem/blob/main/src/sdk/prompts.ts)

### 3. Prompt Builder (`src/server/generation/providers/shared/prompt-builder.ts`)

Handles the generation of structured output schemas for LLM interactions:

```typescript
function buildObservationOutputSchema(mode: ModeConfig): string {
  const types = mode.observation_types.map(t => t.id).join(' | ');
  return [
    '<observation>',
    `  <type>[ ${types} ]</type>`,
    '  <title>...</title>',
    '  <subtitle>...</subtitle>',
    '  <facts><fact>...</fact></facts>',
    '  <narrative>...</narrative>',
    '  <concepts><concept>...</concept></concepts>',
    '  <files_read><file>...</file></files_read>',
    '  <files_modified><file>...</file></files_modified>',
    '</observation>',
  ].join('\n');
}
```

Key features include XML escaping for safe output (`escapeXml()` function) and fallback to default observation types when mode configuration is unavailable.

资料来源：[src/server/generation/providers/shared/prompt-builder.ts:1-80](https://github.com/thedotmack/claude-mem/blob/main/src/server/generation/providers/shared/prompt-builder.ts)

### 4. Viewer UI (`src/ui/viewer/App.tsx`)

The viewer is a React-based web application (default port 8080) providing:

- Real-time observation streaming display
- Session summary cards
- Context settings configuration
- Console log viewing
- Welcome modal for first-time users

```mermaid
graph LR
    A[Viewer App] --> B[ObservationCard]
    A --> C[SummaryCard]
    A --> D[ContextSettingsModal]
    A --> E[LogsDrawer]
```

资料来源：[src/ui/viewer/App.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/App.tsx)

## Data Flow

### Observation Capture Flow

```mermaid
sequenceDiagram
    participant IDE as Claude Code
    participant Hooks as Plugin Hooks
    participant Worker as Worker Service
    participant LLM as Claude API
    participant DB as SQLite DB

    IDE->>Hooks: Tool usage detected
    Hooks->>Worker: POST /observation
    Worker->>Worker: Parse tool_input
    Worker->>LLM: Generate structured observation
    LLM-->>Worker: XML observation
    Worker->>DB: Store observation
    Worker-->>Hooks: Acknowledge
```

### Context Injection Flow

The system injects relevant observations into new sessions based on configurable settings:

| Setting | Default | Description |
|---------|---------|-------------|
| `CLAUDE_MEM_CONTEXT_OBSERVATIONS` | 50 | Number of recent observations to include (1-200) |
| `CLAUDE_MEM_CONTEXT_SESSIONS` | varies | Number of recent sessions to pull from (1-50) |

资料来源：[src/ui/viewer/components/ContextSettingsModal.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/ContextSettingsModal.tsx)

## Observation Data Model

Observations captured include:

| Field | Type | Description |
|-------|------|-------------|
| `id` | integer | Unique identifier |
| `tool_name` | string | Name of the tool invoked |
| `tool_input` | string/JSON | Input parameters to the tool |
| `tool_output` | string/JSON | Output from the tool |
| `title` | string | Generated observation title |
| `subtitle` | string | Brief description |
| `facts` | string[] | Key facts extracted |
| `narrative` | string | Extended narrative description |
| `concepts` | string[] | Concepts learned |
| `files_read` | string[] | Files accessed during observation |
| `files_modified` | string[] | Files changed during observation |

资料来源：[src/ui/viewer/components/ObservationCard.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/ObservationCard.tsx)

## Storage Architecture

Data is persisted locally in `~/.claude-mem`:

- **SQLite Database**: Primary storage for observations and summaries
- **Configuration**: User preferences stored in localStorage (viewer) or environment variables
- **Logs**: Application logs accessible via Viewer UI

## Installation Architecture

The install command (`npx claude-mem install`) handles:

1. Detection of target IDE (Claude Code, Gemini CLI, OpenCode)
2. Installation of plugin hooks
3. Worker service setup
4. Initial startup verification

Supported installation targets:

| IDE | Command | Installation Method |
|-----|---------|---------------------|
| Claude Code | `npx claude-mem install` | Native plugin marketplace |
| Claude Code | `/plugin marketplace add thedotmack/claude-mem` | Built-in plugin command |
| Gemini CLI | `npx claude-mem install --ide gemini-cli` | Auto-detects `~/.gemini` |
| OpenCode | `npx claude-mem install --ide opencode` | Custom integration |

资料来源：[README.md](https://github.com/thedotmack/claude-mem/blob/main/README.md)
资料来源：[src/npx-cli/commands/install.ts](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/commands/install.ts)

## Error Handling

The Viewer UI implements an `ErrorBoundary` component that:

- Catches React component errors
- Displays user-friendly error messages
- Shows detailed error information in expandable sections
- Allows users to refresh and retry

资料来源：[src/ui/viewer/components/ErrorBoundary.tsx](https://github.com/thedotmack/claude-mem/blob/main/src/ui/viewer/components/ErrorBoundary.tsx)

## Summary

Claude-Mem's architecture consists of three main layers:

1. **Integration Layer**: Plugin hooks that intercept tool usage in the IDE
2. **Processing Layer**: Worker service that captures, processes, and stores observations
3. **Presentation Layer**: Web-based viewer for inspecting memory and configuring settings

The system is designed to be IDE-agnostic, supporting multiple AI coding assistants while maintaining a unified storage and processing backend.

---

<a id='page-hooks-system'></a>

## Hooks System and Lifecycle

### 相关页面

相关主题：[System Architecture Overview](#page-architecture-overview), [Worker Service Architecture](#page-worker-service), [Data Flow and Processing](#page-data-flow)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [plugin/hooks/hooks.json](https://github.com/thedotmack/claude-mem/blob/main/plugin/hooks/hooks.json)
- [src/cli/hook-command.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/hook-command.ts)
- [src/shared/hook-constants.ts](https://github.com/thedotmack/claude-mem/blob/main/src/shared/hook-constants.ts)
- [src/cli/handlers/observation.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/handlers/observation.ts)
- [src/cli/handlers/session-init.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/handlers/session-init.ts)
- [src/cli/handlers/user-message.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/handlers/user-message.ts)
- [src/cli/handlers/summarize.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/handlers/summarize.ts)
</details>

# Hooks System and Lifecycle

## Overview

The Hooks System is the core mechanism by which Claude-Mem captures observations, user interactions, and session events from Claude Code to build persistent memory across sessions. The system integrates with Claude Code's plugin hook API to monitor and record agent activities at strategic points in the conversation lifecycle.

Claude-Mem registers multiple hook handlers that fire at different stages: session initialization, user message processing, tool execution, and session termination. Each handler extracts relevant context and stores observations that inform future sessions about project state and progress.

资料来源：[cursor-hooks/README.md](https://github.com/thedotmack/claude-mem/blob/main/cursor-hooks/README.md)

---

## Architecture Overview

### Hook System Components

The hook system consists of three primary layers:

| Layer | Purpose | Location |
|-------|---------|----------|
| **Hook Configuration** | Declares which hooks to register with Claude Code | `plugin/hooks/hooks.json` |
| **Hook Handlers** | TypeScript implementations that process hook events | `src/cli/handlers/*.ts` |
| **Hook Constants** | Shared definitions and configuration | `src/shared/hook-constants.ts` |

资料来源：[src/cli/hook-command.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/hook-command.ts)

### Hook Registration Flow

```mermaid
graph TD
    A[Claude Code Startup] --> B[Load hooks.json]
    B --> C[Register All Hooks]
    C --> D{Hook Event Occurs}
    D -->|PreToolUse| E[observation.ts]
    D -->|PostToolUse| E
    D -->|User| F[user-message.ts]
    D -->|Stop| G[summarize.ts]
    D -->|Start| H[session-init.ts]
    E --> I[Extract Context]
    F --> I
    G --> I
    H --> I
    I --> J[Store Observation]
    J --> K[Memory Index Updated]
```

---

## Hook Types and Handlers

### Hook Configuration Schema

The `hooks.json` file defines the complete hook registration:

```json
{
  "hooks": {
    "Start": [
      {
        "hook": "Start",
        "name": "session-init",
        "path": "<HOOKS_DIR>/session-init.sh"
      }
    ],
    "Stop": [
      {
        "hook": "Stop",
        "name": "session-summary",
        "path": "<HOOKS_DIR>/session-summary.sh"
      }
    ],
    "User": [
      {
        "hook": "User",
        "name": "context-ready",
        "path": "<HOOKS_DIR>/context-ready.sh"
      }
    ],
    "PreToolUse": [...],
    "PostToolUse": [...]
  }
}
```

资料来源：[cursor-hooks/README.md](https://github.com/thedotmack/claude-mem/blob/main/cursor-hooks/README.md)

### Handler Specifications

#### 1. Session Initialization Handler (`session-init.ts`)

Fires when a new Claude Code session begins. Responsible for setting up context for the new session.

**Responsibilities:**
- Detects project root and language context
- Loads recent observations from previous sessions
- Initializes session metadata
- Triggers welcome flow on first session in a project

资料来源：[src/cli/handlers/session-init.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/handlers/session-init.ts)

#### 2. User Message Handler (`user-message.ts`)

Fires when the user submits a new prompt. Captures the user's intent and context.

**Responsibilities:**
- Parses user request and extract key entities
- Identifies files or concepts mentioned
- Correlates with existing observations
- Records user goals for future reference

资料来源：[src/cli/handlers/user-message.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/handlers/user-message.ts)

#### 3. Observation Handler (`observation.ts`)

Fires on tool use events (PreToolUse and PostToolUse). This is the primary handler for capturing agent activities.

**Captures observations for:**
- File reads (Read, Glob, Grep operations)
- File edits (Bash, Write, Edit operations)
- MCP tool executions
- Command outputs and results
- Code modifications

**Observation Data Model:**

| Field | Type | Description |
|-------|------|-------------|
| `id` | string | Unique observation identifier |
| `type` | enum | `file_read`, `file_edit`, `command`, `concept`, `mcp_tool` |
| `tool_name` | string | The Claude tool that was invoked |
| `tool_input` | object | Arguments passed to the tool |
| `tool_output` | string | Result or output from the tool |
| `project` | string | Project identifier |
| `session_id` | string | Current session identifier |
| `created_at` | timestamp | When the observation was recorded |

资料来源：[src/cli/handlers/observation.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/handlers/observation.ts)

#### 4. Session Summary Handler (`summarize.ts`)

Fires when a session ends (Stop hook). Generates semantic summaries of completed work.

**Responsibilities:**
- Analyzes accumulated observations from the session
- Extracts key accomplishments and decisions
- Identifies next steps and pending tasks
- Generates structured summary in XML format

资料来源：[src/cli/handlers/summarize.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/handlers/summarize.ts)

---

## Hook Constants

The `hook-constants.ts` file centralizes shared configuration and constants used across all handlers.

```typescript
// Hook event types
export const HOOK_EVENTS = {
  START: 'Start',
  STOP: 'Stop',
  USER: 'User',
  PRE_TOOL_USE: 'PreToolUse',
  POST_TOOL_USE: 'PostToolUse',
} as const;

// Observation types
export const OBSERVATION_TYPES = {
  FILE_READ: 'file_read',
  FILE_EDIT: 'file_edit',
  COMMAND: 'command',
  CONCEPT: 'concept',
  MCP_TOOL: 'mcp_tool',
} as const;

// Handler configuration
export const HOOK_CONFIG = {
  MAX_OBSERVATIONS_PER_SESSION: 200,
  BATCH_SIZE: 50,
  DEBOUNCE_MS: 100,
} as const;
```

资料来源：[src/shared/hook-constants.ts](https://github.com/thedotmack/claude-mem/blob/main/src/shared/hook-constants.ts)

---

## Lifecycle Flow

### Session Lifecycle Diagram

```mermaid
stateDiagram-v2
    [*] --> SessionStart: Start Hook
    SessionStart --> AwaitingUserInput: Initialize Context
    AwaitingUserInput --> UserMessageReceived: User Prompt
    UserMessageReceived --> ToolExecution: Process Request
    ToolExecution --> ObservationCapture: PreToolUse
    ToolExecution --> ObservationCapture: PostToolUse
    ObservationCapture --> ToolExecution: More Tools?
    ToolExecution --> AwaitingUserInput: Response Ready
    AwaitingUserInput --> SessionEnd: User Exits
    SessionEnd --> SummaryGeneration: Stop Hook
    SummaryGeneration --> [*]: Session Complete
```

### Observation Capture Lifecycle

```mermaid
sequenceDiagram
    participant CC as Claude Code
    participant HH as Hook Handler
    participant API as Memory API
    participant DB as SQLite Store

    CC->>HH: PostToolUse Event
    HH->>HH: Parse Tool Input/Output
    HH->>HH: Extract Context Metadata
    HH->>API: POST /observations
    API->>API: Validate & Enrich
    API->>DB: Store Observation
    DB-->>API: Confirmation
    API-->>HH: 201 Created
    HH-->>CC: Hook Complete
```

---

## Hook Command Interface

The `hook-command.ts` file provides the CLI interface for managing hooks:

```typescript
// Available hook commands
interface HookCommands {
  install(): Promise<void>;      // Register hooks with Claude Code
  uninstall(): Promise<void>;     // Remove hook registration
  status(): Promise<HookStatus>; // Check hook registration status
  reload(): Promise<void>;        // Reload hook handlers
}
```

**CLI Commands:**

| Command | Description |
|---------|-------------|
| `npx claude-mem hooks install` | Register all hooks with Claude Code |
| `npx claude-mem hooks uninstall` | Remove hook registration |
| `npx claude-mem hooks status` | Display current hook status |
| `npx claude-mem hooks reload` | Hot-reload hook handlers |

资料来源：[src/cli/hook-command.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/hook-command.ts)

---

## Cursor Hooks Compatibility

Claude-Mem also provides a Cursor hooks implementation for users working in Cursor IDE:

| Feature | Claude Code | Cursor |
|---------|-------------|--------|
| Hook Configuration | `hooks.json` | `hooks.json` |
| Session Init | `PostToolUse` hook | `afterMCPExecution`, `afterShellExecution`, `afterFileEdit` |
| Observation Capture | `PostToolUse` hook | `afterMCPExecution`, `afterShellExecution`, `afterFileEdit` |
| Session Summary | `Stop` hook with transcript | `stop` hook (limited transcript) |
| MCP Search Tools | Full support | Full support (if MCP configured) |

**Files in Cursor Hooks Implementation:**
- `hooks.json` - Hook configuration
- `common.sh` - Shared utility functions
- `session-init.sh` - Session initialization
- `context-inject.sh` - Context/worker readiness hook
- `save-observation.sh` - MCP and shell observation capture
- `save-file-edit.sh` - File edit observation capture
- `session-summary.sh` - Summary generation
- `cursorrules-template.md` - Template for `.cursorrules` file

资料来源：[cursor-hooks/README.md](https://github.com/thedotmack/claude-mem/blob/main/cursor-hooks/README.md)

---

## Configuration Options

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `CLAUDE_MEM_HOOKS_ENABLED` | `true` | Enable/disable all hooks |
| `CLAUDE_MEM_OBSERVATIONS_LIMIT` | `50` | Max observations per context injection |
| `CLAUDE_MEM_SESSIONS_LIMIT` | `10` | Max sessions to pull observations from |
| `CLAUDE_MEM_HOOK_LOG_LEVEL` | `info` | Logging verbosity |
| `CLAUDE_MEM_WELCOME_HINT_ENABLED` | `true` | Show first-session welcome |

### Hook Filtering

Handlers can filter observations based on:

- **Tool names**: Only capture specific tools (e.g., `Read`, `Write`, `Bash`)
- **File patterns**: Include/exclude files by glob patterns
- **Command patterns**: Filter shell commands by regex
- **Content thresholds**: Ignore trivial operations (empty reads, etc.)

---

## Error Handling

Hook handlers implement robust error handling:

1. **Graceful Degradation**: If a handler fails, the session continues
2. **Retry Logic**: Transient failures trigger exponential backoff retries
3. **Dead Letter Queue**: Failed observations are queued for retry
4. **Logging**: All errors are logged with full context for debugging

```typescript
// Error handling pattern
try {
  await processHookEvent(event);
} catch (error) {
  logger.error('Hook handler failed', { error, event });
  // Don't rethrow - allow session to continue
}
```

资料来源：[src/cli/handlers/observation.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/handlers/observation.ts)

---

## Summary

The Hooks System provides Claude-Mem's core observation capture mechanism. By registering handlers at strategic points in Claude Code's lifecycle—session start, user input, tool execution, and session end—the system builds a comprehensive memory of project activities. This memory enables Claude to maintain context across sessions, recall previous decisions, and understand project history.

Key characteristics:
- **Event-driven**: Reactive to Claude Code's native hook system
- **Non-blocking**: Failures don't interrupt user workflow
- **Comprehensive**: Captures reads, writes, commands, and concepts
- **Structured**: All observations follow a consistent schema
- **Extensible**: New handlers can be added for additional observability

---

<a id='page-worker-service'></a>

## Worker Service Architecture

### 相关页面

相关主题：[System Architecture Overview](#page-architecture-overview), [Database Schema and Storage](#page-database-schema), [MCP Tools and Context Generation](#page-mcp-tools)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/services/worker-service.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker-service.ts)
- [src/server/jobs/ServerJobQueue.ts](https://github.com/thedotmack/claude-mem/blob/main/src/server/jobs/ServerJobQueue.ts)
- [src/services/worker/ClaudeProvider.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/ClaudeProvider.ts)
- [src/services/worker/GeminiProvider.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/GeminiProvider.ts)
- [src/services/worker/OpenRouterProvider.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/OpenRouterProvider.ts)
- [src/services/worker/http/routes/MemoryRoutes.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/http/routes/MemoryRoutes.ts)
- [src/npx-cli/commands/runtime.ts](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/commands/runtime.ts)
- [src/services/infrastructure/ProcessManager.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/infrastructure/ProcessManager.ts)
</details>

# Worker Service Architecture

The Worker Service is the core backend component of claude-mem, responsible for processing, storing, and serving memory observations across Claude Code sessions. It runs as a persistent background service that handles LLM inference, observation generation, and semantic search operations.

## Overview

The Worker Service operates independently from Claude Code sessions, maintaining a long-running process that:

- Receives tool usage observations from Claude Code via plugin hooks
- Generates semantic summaries using configured LLM providers (Claude, Gemini, OpenRouter)
- Stores observations in a local SQLite database with Chroma vector embeddings
- Serves a web-based viewer UI and REST API for browsing and querying memories

```mermaid
graph TD
    subgraph "Claude Code"
        A[Tool Execution] --> B[Plugin Hooks]
        B --> C[Tool Result Persist Event]
    end
    
    subgraph "Worker Service"
        D[HTTP Server :37777] --> E[Route Handlers]
        E --> F[Session Manager]
        F --> G[Observation Generator]
        G --> H[LLM Providers]
        H --> I[Database Manager]
        I --> J[SQLite + Chroma]
    end
    
    C -->|SSE/WebSocket| D
    D -->|Viewer UI| K[Browser Client]
    D -->|REST API| L[External Clients]
```

## Core Components

### WorkerService

The main service orchestrator located in `src/services/worker-service.ts`. It initializes all sub-components, registers HTTP routes, manages lifecycle events, and coordinates between the UI and backend processing.

**Key Responsibilities:**

| Responsibility | Description |
|----------------|-------------|
| Lifecycle Management | Coordinates startup/shutdown of all service components |
| Route Registration | Registers ViewerRoutes, SessionRoutes, DataRoutes, SettingsRoutes, LogsRoutes, MemoryRoutes |
| Middleware | Implements initialization check middleware (returns 503 during DB init) |
| Database Initialization | Ensures SQLite and Chroma are ready before accepting requests |
| SSE Broadcasting | Manages real-time event streaming to connected clients |

资料来源：[src/services/worker-service.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker-service.ts)

### Session Manager

Manages individual Claude Code session lifecycles, tracking active sessions and coordinating observation generation per session.

资料来源：[src/services/worker/SessionManager.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/SessionManager.ts)

## LLM Provider Architecture

The Worker Service supports multiple LLM backends through a provider abstraction pattern.

### Provider Comparison

| Provider | Class | Purpose | API Endpoint |
|----------|-------|---------|--------------|
| Anthropic Claude | `ClaudeProvider` | Primary observation generation | api.anthropic.com |
| Google Gemini | `GeminiProvider` | Alternative generation | Generative Language API |
| OpenRouter | `OpenRouterProvider` | Unified multi-model access | openrouter.ai |

资料来源：
- [src/services/worker/ClaudeProvider.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/ClaudeProvider.ts)
- [src/services/worker/GeminiProvider.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/GeminiProvider.ts)
- [src/services/worker/OpenRouterProvider.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/OpenRouterProvider.ts)

### Provider Selection

The system automatically selects providers based on:
1. Configuration in `~/.claude-mem/settings.json`
2. Available API keys in environment variables
3. Fallback to Claude as primary provider

## HTTP Route Architecture

The Worker Service exposes REST endpoints through registered route handlers:

```mermaid
graph LR
    A[HTTP :37777] --> B[ViewerRoutes]
    A --> C[SessionRoutes]
    A --> D[DataRoutes]
    A --> E[SettingsRoutes]
    A --> F[LogsRoutes]
    A --> G[MemoryRoutes]
    A --> H[ServerV1Routes]
```

### Route Groups

| Route | File | Purpose |
|-------|------|---------|
| Viewer | `ViewerRoutes` | Serves the web-based memory viewer UI |
| Session | `SessionRoutes` | Manages session lifecycle, continuation prompts |
| Data | `DataRoutes` | Pagination, filtering, observation retrieval |
| Settings | `SettingsRoutes` | User preferences and configuration |
| Logs | `LogsRoutes` | Service logging and diagnostics |
| Memory | `MemoryRoutes` | Memory CRUD operations, search |
| V1 API | `ServerV1Routes` | Legacy compatibility endpoints |

资料来源：[src/services/worker/http/routes/MemoryRoutes.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/http/routes/MemoryRoutes.ts)

## Job Queue System

Observation generation is handled asynchronously through a BullMQ-based job queue system.

### Queue Configuration

```typescript
interface QueueConfig {
  connection: RedisConnectionConfig;
  prefix: string;
  defaultJobOptions: {
    attempts: number;
    backoff: { type: 'exponential'; delay: number };
    removeOnComplete: boolean;
  };
}
```

资料来源：[src/server/jobs/ServerJobQueue.ts](https://github.com/thedotmack/claude-mem/blob/main/src/server/jobs/ServerJobQueue.ts)

### Event Handling

The queue emits events for observability:

| Event | Handler | Description |
|-------|---------|-------------|
| `completed` | `onCompleted` | Job finished successfully |
| `failed` | `onFailed` | Job failed after all retries |
| `progress` | `onProgress` | Job reported progress percentage |
| `stalled` | `notifyStalled` | Job became unresponsive |

## Process Management

The Worker Service can run in multiple modes:

```mermaid
graph TD
    A[Start Command] --> B{IDE Type}
    B -->|claude-code| C[Claude Code Plugin Mode]
    B -->|gemini-cli| D[Gemini CLI Mode]
    B -->|opencode| E[OpenCode Mode]
    
    C --> F[Persistent Background Process]
    D --> F
    E --> F
    F --> G[Supervisor Process]
    G --> H[Worker Service :37777]
```

### Runtime Modes

| Mode | Activation | Behavior |
|------|------------|----------|
| Auto-start | Default | Worker starts automatically on first session |
| Manual | `npx claude-mem start` | Explicit user initiation |
| Background | Supervisor-managed | Persistent daemon with health monitoring |

资料来源：[src/npx-cli/commands/runtime.ts](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/commands/runtime.ts)

### Process Manager

The `ProcessManager` handles:

- Spawning and monitoring worker processes
- Health check endpoints (`/health`, `/readiness`)
- Automatic restart on crash
- Graceful shutdown handling

资料来源：[src/services/infrastructure/ProcessManager.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/infrastructure/ProcessManager.ts)

## Configuration

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `CLAUDE_MEM_WORKER_PORT` | `37777` | Worker HTTP server port |
| `CLAUDE_MEM_WORKER_HOST` | `localhost` | Worker binding host |
| `CLAUDE_MEM_MODE` | - | Active mode configuration |
| `CLAUDE_MEM_WELCOME_HINT_ENABLED` | `true` | Show first-use hints |

### Service Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/health` | GET | Basic health check |
| `/readiness` | GET | Readiness probe (DB initialized) |
| `/version` | GET | Service version info |
| `/chroma/status` | GET | Vector database status |

## Startup Sequence

```mermaid
sequenceDiagram
    participant User
    participant Plugin as Claude Code Plugin
    participant Worker as Worker Service
    participant DB as SQLite/Chroma
    participant Queue as Job Queue

    User->>Plugin: First Claude Code session
    Plugin->>Worker: Tool result events
    Worker->>DB: Initialize connections
    DB-->>Worker: Ready
    Worker->>Queue: Start worker process
    Queue->>Worker: Ready
    Worker-->>Plugin: Service available
    Plugin->>Worker: Stream observations
    Worker->>Queue: Enqueue generation jobs
    Queue->>Worker: Process observations
    Worker->>DB: Store summaries
```

## Data Flow

### Observation Lifecycle

1. **Capture**: Plugin captures tool execution events (read, edit, shell commands)
2. **Transmission**: Events sent via SSE to Worker Service
3. **Queuing**: Jobs added to BullMQ generation queue
4. **Processing**: LLM provider generates semantic summary
5. **Storage**: SQLite stores structured data, Chroma stores vector embeddings
6. **Retrieval**: Future sessions query relevant observations via semantic search

资料来源：[src/services/worker-service.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker-service.ts)

## Error Handling

### Initialization Guard

During startup, the service returns HTTP 503 for all requests except health/readiness checks:

```
Request → Middleware Check → DB Initialized?
                              ├─ Yes → Pass through to routes
                              └─ No → 503 "Service initializing"
```

### Queue Failure Handling

Failed jobs trigger listener callbacks:

```typescript
w.on('failed', (jobId: string, error: Error) => {
  for (const l of this.listeners) {
    l.onFailed?.(jobId, attemptsMade, error.message);
  }
});
```

资料来源：[src/server/jobs/ServerJobQueue.ts](https://github.com/thedotmack/claude-mem/blob/main/src/server/jobs/ServerJobQueue.ts)

## Extension Points

### Custom LLM Providers

Providers implement a common interface allowing:

- Custom API endpoints
- Different authentication methods
- Provider-specific prompt formatting
- Rate limiting and retry policies

### Mode System

The Worker Service supports configurable modes via `ModeConfig` that define:

- Observation types to capture
- Prompt templates for generation
- Summary output formats
- System identity instructions

## Security Considerations

- Service binds to localhost by default
- No authentication on local-only deployments
- All data stored in `~/.claude-mem` directory
- API keys loaded from environment variables

---

<a id='page-database-schema'></a>

## Database Schema and Storage

### 相关页面

相关主题：[System Architecture Overview](#page-architecture-overview), [Data Flow and Processing](#page-data-flow), [Search Architecture](#page-search-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/services/sqlite/schema.sql](https://github.com/thedotmack/claude-mem/blob/main/src/services/sqlite/schema.sql)
- [src/services/sqlite/SessionStore.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/sqlite/SessionStore.ts)
- [src/services/sqlite/Observations.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/sqlite/Observations.ts)
- [src/services/sqlite/Summaries.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/sqlite/Summaries.ts)
- [src/services/sqlite/Timeline.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/sqlite/Timeline.ts)
- [src/services/sqlite/migrations.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/sqlite/migrations.ts)
- [src/services/sqlite/migrations/runner.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/sqlite/migrations/runner.ts)
- [src/storage/sqlite/schema.ts](https://github.com/thedotmack/claude-mem/blob/main/src/storage/sqlite/schema.ts)
</details>

# Database Schema and Storage

## Overview

Claude-Mem uses SQLite as its primary persistent storage layer to maintain session continuity, store observations, and preserve learned context across sessions. The database schema captures the complete lifecycle of AI sessions, including tool usage, observations, summaries, and temporal data for timeline reconstruction.

The storage system is designed to support:
- Multi-session tracking with unique identifiers
- Observation persistence with semantic metadata
- Session summarization storage
- Timeline event reconstruction
- Project-based organization

## Architecture

```mermaid
graph TD
    A[Worker Service] --> B[DBManager]
    B --> C[SQLite Database]
    C --> D[schema_versions]
    C --> E[sdk_sessions]
    C --> F[observations]
    C --> G[session_summaries]
    C --> H[pending_messages]
    C --> I[user_prompts]
    C --> J[projects]
    
    K[SessionStore] -.-> E
    L[Observations] -.-> F
    M[Summaries] -.-> G
    N[Timeline] -.-> J
```

## Core Tables

### schema_versions

Tracks applied database migrations to ensure schema consistency across upgrades.

| Column | Type | Description |
|--------|------|-------------|
| version | INTEGER PRIMARY KEY | Migration version number |
| applied_at | TEXT | ISO timestamp of migration application |

资料来源：[src/services/sqlite/migrations/runner.ts:1-50]()

### sdk_sessions

Stores metadata about each Claude session managed by the SDK.

| Column | Type | Description |
|--------|------|-------------|
| id | INTEGER PRIMARY KEY | Auto-incrementing row ID |
| memory_session_id | TEXT NOT NULL | Unique session identifier |
| content_session_id | TEXT NOT NULL | Content/session reference ID |
| project | TEXT NOT NULL | Project name for grouping |
| status | TEXT | Session status (active/completed/etc) |
| created_at | TEXT NOT NULL | Creation timestamp |
| created_at_epoch | INTEGER NOT NULL | Epoch timestamp for sorting |

资料来源：[src/services/sqlite/migrations/runner.ts:60-90]()

### observations

Records tool usage observations captured during sessions. Observations are the primary mechanism for preserving learned context.

| Column | Type | Description |
|--------|------|-------------|
| id | INTEGER PRIMARY KEY | Auto-incrementing observation ID |
| memory_session_id | TEXT NOT NULL | Foreign key to sdk_sessions |
| tool_name | TEXT | Name of the tool used |
| tool_input | TEXT | JSON-encoded tool input |
| tool_output | TEXT | JSON-encoded tool output |
| observation_type | TEXT | Type classification (fact, decision, etc.) |
| title | TEXT | Observation title |
| subtitle | TEXT | Brief description |
| narrative | TEXT | Detailed narrative |
| concepts | TEXT | JSON array of concept tags |
| files_read | TEXT | JSON array of files read |
| files_modified | TEXT | JSON array of files modified |
| created_at | TEXT NOT NULL | Creation timestamp |
| created_at_epoch | INTEGER NOT NULL | Epoch timestamp |

资料来源：[src/services/sqlite/SessionStore.ts](), [src/services/sqlite/Observations.ts]()

### session_summaries

Stores AI-generated summaries of completed sessions, capturing requests, findings, and next steps.

| Column | Type | Description |
|--------|------|-------------|
| id | INTEGER PRIMARY KEY | Auto-incrementing summary ID |
| memory_session_id | TEXT NOT NULL | Foreign key to sdk_sessions |
| project | TEXT NOT NULL | Project name |
| request | TEXT | Original user request |
| investigated | TEXT | What was investigated |
| learned | TEXT | Key learnings |
| completed | TEXT | Completed work |
| next_steps | TEXT | Planned next steps |
| files_read | TEXT | Files read during session |
| files_edited | TEXT | Files modified during session |
| notes | TEXT | Additional notes |
| prompt_number | INTEGER | Session prompt sequence number |
| created_at | TEXT NOT NULL | Creation timestamp |
| created_at_epoch | INTEGER NOT NULL | Epoch timestamp |

资料来源：[src/services/sqlite/migrations/runner.ts:50-80](), [src/services/sqlite/Summaries.ts]()

### pending_messages

Queue table for messages awaiting processing by the worker service.

| Column | Type | Description |
|--------|------|-------------|
| id | INTEGER PRIMARY KEY | Auto-incrementing message ID |
| content_session_id | TEXT NOT NULL | Session reference |
| message_id | INTEGER | Claude message ID |
| message_type | TEXT | Message type (observation/summarize) |
| payload | TEXT | JSON message payload |
| status | TEXT | Processing status |
| created_at | TEXT NOT NULL | Creation timestamp |
| created_at_epoch | INTEGER NOT NULL | Epoch timestamp |
| failed_at_epoch | INTEGER | Epoch timestamp of last failure |

资料来源：[src/services/sqlite/migrations/runner.ts:200-230]()

### user_prompts

Stores original user prompts for each session.

| Column | Type | Description |
|--------|------|-------------|
| id | INTEGER PRIMARY KEY | Auto-incrementing prompt ID |
| content_session_id | TEXT NOT NULL | Session reference |
| prompt | TEXT NOT NULL | User prompt text |
| created_at | TEXT NOT NULL | Creation timestamp |
| created_at_epoch | INTEGER NOT NULL | Epoch timestamp |

### projects

Maintains project registry for organizing sessions and observations.

| Column | Type | Description |
|--------|------|-------------|
| id | INTEGER PRIMARY KEY | Auto-incrementing project ID |
| name | TEXT NOT NULL UNIQUE | Project name |
| created_at | TEXT NOT NULL | Creation timestamp |

资料来源：[src/storage/sqlite/schema.ts](), [src/services/sqlite/Timeline.ts]()

## Schema Migrations

The system uses a versioned migration system to handle schema evolution. Migrations are applied sequentially and tracked in the `schema_versions` table.

### Migration Version History

| Version | Description |
|---------|-------------|
| 7 | Session summaries table creation with UNIQUE constraint removal |
| 17 | Column renames: `sdk_session_id` → `memory_session_id`, `claude_session_id` → `content_session_id` |
| 20 | Added `failed_at_epoch` column to `pending_messages` |

资料来源：[src/services/sqlite/migrations/runner.ts:40-45](), [src/services/sqlite/migrations/runner.ts:150-180](), [src/services/sqlite/migrations/runner.ts:195-220]()

### Migration Execution

Migrations are executed via the `MigrationRunner` class which:

1. Checks current schema version from `schema_versions`
2. Applies pending migrations in order
3. Records each applied version with timestamp
4. Handles safe column renaming (only if column exists)

```typescript
private addFailedAtEpochColumn(): void {
  const applied = this.db.prepare('SELECT version FROM schema_versions WHERE version = ?').get(20);
  if (applied) return;
  
  const tableInfo = this.db.query('PRAGMA table_info(pending_messages)').all();
  const hasColumn = tableInfo.some(col => col.name === 'failed_at_epoch');
  
  if (!hasColumn) {
    this.db.run('ALTER TABLE pending_messages ADD COLUMN failed_at_epoch INTEGER');
  }
}
```

资料来源：[src/services/sqlite/migrations/runner.ts:195-215]()

## Session ID Naming Convention

The system underwent a terminology migration in version 17:

| Old Name | New Name | Purpose |
|----------|----------|---------|
| `sdk_session_id` | `memory_session_id` | Primary session identifier across memory system |
| `claude_session_id` | `content_session_id` | Claude/Content API session reference |

This rename reflects the system's expansion beyond Claude Code to support other AI platforms (Gemini CLI, OpenClaw).

资料来源：[src/services/sqlite/migrations/runner.ts:145-170]()

## Data Access Layer

### SessionStore

Provides CRUD operations for session management:

```typescript
interface SessionStore {
  createSession(session: Session): Promise<number>;
  getSession(memorySessionId: string): Promise<Session | null>;
  updateSessionStatus(sessionDbId: number, status: string): Promise<void>;
  listSessions(project?: string): Promise<Session[]>;
}
```

### Observations

Handles observation persistence and retrieval:

```typescript
interface ObservationsStore {
  createObservation(obs: Observation): Promise<number>;
  getObservationsBySession(memorySessionId: string): Promise<Observation[]>;
  searchObservations(query: SearchQuery): Promise<Observation[]>;
  getRecentObservations(limit: number): Promise<Observation[]>;
}
```

### Summaries

Manages session summary storage:

```typescript
interface SummariesStore {
  createSummary(summary: SessionSummary): Promise<number>;
  getSummaryBySession(memorySessionId: string): Promise<SessionSummary | null>;
  listSummaries(project?: string, limit?: number): Promise<SessionSummary[]>;
}
```

### Timeline

Provides temporal queries for reconstructing session history:

```typescript
interface TimelineStore {
  getEventsByDateRange(start: Date, end: Date): Promise<TimelineEvent[]>;
  getSessionTimeline(memorySessionId: string): Promise<TimelineEvent[]>;
  getProjectTimeline(projectName: string): Promise<TimelineEvent[]>;
}
```

## Indexes

The schema includes optimized indexes for common query patterns:

| Index Name | Table | Columns |
|------------|-------|---------|
| idx_session_summaries_sdk_session | session_summaries | memory_session_id |
| idx_session_summaries_project | session_summaries | project |
| idx_session_summaries_created | session_summaries | created_at_epoch |

资料来源：[src/services/sqlite/migrations/runner.ts:85-95]()

## Database Initialization Flow

```mermaid
sequenceDiagram
    participant App as Worker Service
    participant DB as DBManager
    participant Migrate as MigrationRunner
    participant SQLite as SQLite DB
    
    App->>DB: Initialize database connection
    DB->>Migrate: Run pending migrations
    Migrate->>SQLite: SELECT version FROM schema_versions
    SQLite-->>Migrate: Current versions
    Migrate->>SQLite: Apply missing migrations
    Migrate->>SQLite: INSERT INTO schema_versions
    DB->>SQLite: Register prepared statements
    DB-->>App: Database ready
```

## Configuration

The database location is determined by environment variables:

| Variable | Default | Description |
|----------|---------|-------------|
| `CLAUDE_MEM_DB_PATH` | `~/.claude-mem/memory.db` | SQLite database file path |
| `CLAUDE_MEM_WORKER_PORT` | `37777` | Worker service port (related service) |

## Data Flow

```mermaid
graph LR
    A[Claude Session] -->|Tool Usage| B[Observation Capture]
    B --> C[pending_messages]
    C -->|Processing| D[Worker Service]
    D -->|Store| E[observations]
    D -->|Generate| F[session_summaries]
    E -->|Retrieve| G[Future Sessions]
    F -->|Retrieve| G
```

## Related Documentation

- [Worker Service Architecture](../services/worker-service.md)
- [Observations System](../core/observations.md)
- [Session Management](../services/session-manager.md)

---

<a id='page-data-flow'></a>

## Data Flow and Processing

### 相关页面

相关主题：[System Architecture Overview](#page-architecture-overview), [Database Schema and Storage](#page-database-schema), [Hooks System and Lifecycle](#page-hooks-system)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/services/context/ContextBuilder.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/context/ContextBuilder.ts)
- [src/services/context/ObservationCompiler.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/context/ObservationCompiler.ts)
- [src/services/transcripts/processor.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/transcripts/processor.ts)
- [src/services/transcripts/watcher.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/transcripts/watcher.ts)
- [src/server/generation/ProviderObservationGenerator.ts](https://github.com/thedotmack/claude-mem/blob/main/src/server/generation/ProviderObservationGenerator.ts)
- [src/cli/handlers/context.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/handlers/context.ts)
</details>

# Data Flow and Processing

## Overview

Claude-Mem implements a sophisticated data pipeline that captures, processes, stores, and retrieves contextual information from Claude Code sessions. The system transforms raw transcript data into structured observations and summaries that can be injected into future sessions, enabling persistent memory across sessions.

The data flow architecture spans multiple layers: **ingestion** (capturing session activity), **processing** (generating structured observations), **storage** (persisting to local filesystem), **retrieval** (searching and filtering), and **injection** (presenting relevant context to Claude).

## System Architecture

```mermaid
graph TD
    subgraph Ingestion ["Ingestion Layer"]
        TW[Transcript Watcher] --> TP[Transcript Processor]
        TP --> OG[Observation Generator]
    end
    
    subgraph Processing ["Processing Layer"]
        OG --> CB[Context Builder]
        CB --> OC[Observation Compiler]
        OC --> Q[Job Queue]
        Q --> QW[Queue Worker]
    end
    
    subgraph Storage ["Storage Layer"]
        QW --> FS[File System<br/>~/.claude-mem]
        FS --> OBS[Observations DB]
        FS --> SUMM[Summary DB]
    end
    
    subgraph Retrieval ["Retrieval Layer"]
        CLI[CLI Context Handler] --> SR[Search & Retrieval]
        SR --> CB
        CB --> CONTEXT[Context Injection]
    end
    
    subgraph Output ["Output Layer"]
        CONTEXT --> UI[Viewer UI]
        CONTEXT --> SDK[SDK Prompts]
    end
```

## Core Data Flow Pipeline

### 1. Transcript Watching

The transcript watcher monitors Claude Code sessions in real-time, capturing all activity as it occurs.

**Key Components:**

| Component | File | Purpose |
|-----------|------|---------|
| TranscriptWatcher | `src/services/transcripts/watcher.ts` | Monitors transcript files for changes |
| TranscriptProcessor | `src/services/transcripts/processor.ts` | Parses and extracts events from transcripts |

The watcher detects when new content is written to transcript files and triggers processing. Events captured include:

- Tool invocations (`Read`, `Write`, `Edit`, `Bash`, etc.)
- User prompts
- Assistant responses
- System events

### 2. Observation Generation

Observations are generated from processed transcript events using LLM providers.

```mermaid
graph LR
    subgraph Input
        EV[Event Data] --> PG[Prompt Builder]
        MC[Mode Config] --> PG
    end
    
    subgraph Generation
        PG --> LLM[LLM Provider]
        LLM --> XML[XML Output]
    end
    
    subgraph Output
        XML --> OBS[Observation Record]
        XML --> PRIV[Private Data Check]
    end
```

**ProviderObservationGenerator** handles the generation flow:

1. Builds prompts using `ModeConfig` and observation types
2. Sends requests to configured LLM provider (Claude by default)
3. Parses XML-structured responses
4. Validates and sanitizes output

The generated observation schema follows this structure:

```xml
<observation>
  <type>[ observation | decision | change | how-it-works ]</type>
  <title>...</title>
  <subtitle>...</subtitle>
  <facts>
    <fact>...</fact>
    <fact>...</fact>
  </facts>
  <narrative>...</narrative>
  <concepts>
    <concept>...</concept>
  </concepts>
  <files_read>
    <file>...</file>
  </files_read>
  <files_modified>
    <file>...</file>
  </files_modified>
</observation>
```

资料来源：[src/server/generation/providers/shared/prompt-builder.ts](https://github.com/thedotmack/claude-mem/blob/main/src/server/generation/providers/shared/prompt-builder.ts)

### 3. Context Building

The ContextBuilder assembles relevant observations and summaries for injection into new sessions.

| Method | Purpose |
|--------|---------|
| `buildContext()` | Constructs complete context from observations |
| `getRecentContext()` | Retrieves most recent observations |
| `getContextByProject()` | Filters context by project identifier |
| `getContextByFile()` | Retrieves observations related to specific files |

Context building supports multiple retrieval strategies:

- **Timeline-based**: Recent observations first
- **Concept-based**: Match by extracted concepts
- **File-based**: Related to currently accessed files
- **Hybrid**: Combination of above strategies

资料来源：[src/services/context/ContextBuilder.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/context/ContextBuilder.ts)

### 4. Observation Compilation

The ObservationCompiler aggregates and formats observations for different output contexts.

```mermaid
graph TD
    OBS[Raw Observations] --> COMP[ObservationCompiler]
    COMP --> FORM[Format Selection]
    FORM --> MD[Markdown Format]
    FORM --> SDK[SDK Prompt Format]
    FORM --> API[API JSON Format]
    
    MD --> OUT1[Claude.md Files]
    SDK --> OUT2[Session Injection]
    API --> OUT3[REST API Response]
```

Compilation includes:

- **Deduplication**: Removes duplicate observations
- **Ranking**: Scores by relevance and recency
- **Truncation**: Limits context size for token budgets
- **Formatting**: Converts to target output format

资料来源：[src/services/context/ObservationCompiler.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/context/ObservationCompiler.ts)

## Job Queue Processing

Observations and summaries are processed asynchronously through BullMQ job queues.

```mermaid
sequenceDiagram
    participant Watcher
    participant Queue as Job Queue
    participant Worker
    participant Storage
    
    Watcher->>Queue: Add observation job
    Queue->>Worker: Distribute job
    Worker->>Storage: Store observation
    Worker->>Queue: Mark complete
    Queue->>Watcher: Notify success
    
    Note over Worker: Retry on failure<br/>Max 3 attempts
```

**ServerJobQueue** manages job lifecycle:

| Feature | Description |
|---------|-------------|
| Retry Policy | Automatic retry with exponential backoff |
| Progress Tracking | Real-time job progress events |
| Stalled Detection | Monitors for stuck jobs |
| Cross-Process Events | Redis pub/sub for distributed workers |

资料来源：[src/server/jobs/ServerJobQueue.ts](https://github.com/thedotmack/claude-mem/blob/main/src/server/jobs/ServerJobQueue.ts)

## Storage Architecture

All data persists to `~/.claude-mem/` on the local filesystem.

```mermaid
graph TD
    subgraph "~/.claude-mem"
        OBS[observations/]
        SUMM[summary/]
        CONTEXT[context/]
        CONFIG[config.json]
        MODES[modes/]
    end
    
    OBS --> |JSON files| RECORDS[Individual records]
    SUMM --> |JSON files| SESSION_SUMM[Session summaries]
    CONTEXT --> |Compiled| READY[Ready for injection]
```

### File Structure

| Directory | Content | Format |
|-----------|---------|--------|
| `observations/` | Individual observations | JSON with metadata |
| `summary/` | Session summaries | JSON with sections |
| `context/` | Compiled context bundles | JSON arrays |
| `modes/` | Mode configurations | JSON |
| `transcripts/` | Raw session transcripts | Text/markdown |

## Summary Generation Flow

Summaries are generated at session end to provide high-level overviews.

```mermaid
graph TD
    subgraph SessionEnd
        END[Session Complete] --> EXTRACT[Extract Key Events]
        EXTRACT --> BUILD[Build Summary Prompt]
    end
    
    subgraph Generation
        BUILD --> LLM[LLM Generation]
        LLM --> PARSE[Parse Summary XML]
    end
    
    subgraph Output
        PARSE --> STRUCT[Structured Summary]
        STRUCT --> STORE[Store to summary/]
        STRUCT --> DISPLAY[Display in UI]
    end
```

Summary output format:

```xml
<summary>
  <request>Original user request</request>
  <investigated>What was explored</investigated>
  <learned>Key discoveries</learned>
  <completed>Tasks accomplished</completed>
  <next_steps>Follow-up items</next_steps>
  <notes>Additional context</notes>
</summary>
```

资料来源：[src/sdk/prompts.ts](https://github.com/thedotmack/claude-mem/blob/main/src/sdk/prompts.ts)

## CLI Context Handler

The CLI provides programmatic access to context operations.

**Available Commands:**

| Command | Purpose |
|---------|---------|
| `/learn-codebase` | Ingest entire repository |
| `/context inject` | Manually inject context |
| `/context search` | Search observations |
| `/context clear` | Clear project context |

资料来源：[src/cli/handlers/context.ts](https://github.com/thedotmack/claude-mem/blob/main/src/cli/handlers/context.ts)

## Data Models

### Observation Model

```typescript
interface Observation {
  id: string;
  type: ObservationType;
  title: string;
  subtitle?: string;
  facts: string[];
  narrative?: string;
  concepts: string[];
  files_read: string[];
  files_modified: string[];
  created_at_epoch: number;
  project?: string;
  session_id?: string;
}
```

### Summary Model

```typescript
interface Summary {
  id: string;
  request: string;
  investigated: string;
  learned: string;
  completed: string;
  next_steps: string;
  notes?: string;
  project: string;
  created_at_epoch: number;
}
```

## Context Injection Flow

When a new session starts, relevant context is automatically injected:

```mermaid
sequenceDiagram
    participant Session as New Session
    participant Builder as ContextBuilder
    participant Store as Storage
    participant Claude as Claude LLM
    
    Session->>Builder: Request context
    Builder->>Store: Query observations
    Store->>Builder: Return ranked results
    Builder->>Builder: Compile context
    Builder->>Session: Inject context
    Session->>Claude: Request with context
    Claude->>Session: Contextual response
```

Injection includes:
- Recent observations (configurable count)
- Project-specific summaries
- Related file history
- Concept tags for relevance

## Configuration Options

| Environment Variable | Default | Purpose |
|---------------------|---------|---------|
| `CLAUDE_MEM_WORKER_PORT` | `37777` | Worker service port |
| `RAGTIME_TRANSCRIPT_MAX_AGE` | `24` | Transcript retention (hours) |
| `RAGTIME_SESSION_DELAY` | `2000` | Delay between sessions (ms) |

资料来源：[ragtime/README.md](https://github.com/thedotmack/claude-mem/blob/main/ragtime/README.md)

## Key Processing Pipelines

### 1. Passive Observation Capture

```
Session Activity → Watcher → Processor → Generator → Queue → Storage
```

- Automatic, background processing
- No user intervention required
- Builds memory passively during work

### 2. Active Codebase Ingestion

```
User Command (/learn-codebase) → File Parser → Context Builder → Storage
```

- Triggered manually by user
- Parses entire codebase structure
- Creates file-level observations

资料来源：[src/services/smart-file-read/parser.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/smart-file-read/parser.ts)

### 3. Context Retrieval & Injection

```
New Session → Context Handler → Search → Compile → Inject → LLM
```

- Triggered at session start
- Selects relevant observations
- Formats for LLM consumption

## Security Considerations

### Private Data Handling

The system implements safeguards for sensitive data:

1. **Pattern Detection**: Identifies potential secrets before processing
2. **XML Escaping**: All output properly escaped to prevent injection
3. **File Path Validation**: Prevents写入 to protected directories

```typescript
function escapeXml(text: string): string {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}
```

资料来源：[src/server/generation/providers/shared/prompt-builder.ts](https://github.com/thedotmack/claude-mem/blob/main/src/server/generation/providers/shared/prompt-builder.ts)

## Summary

The data flow and processing system in Claude-Mem consists of five integrated layers:

1. **Ingestion Layer** - Captures session activity via transcript watching
2. **Processing Layer** - Generates structured observations using LLM providers
3. **Storage Layer** - Persists all data to local filesystem with JSON format
4. **Retrieval Layer** - Searches and compiles relevant context on demand
5. **Injection Layer** - Presents context to Claude Code sessions

The asynchronous job queue architecture ensures reliable processing even under high load, while the flexible context builder supports multiple retrieval strategies for optimal memory recall.

---

<a id='page-search-architecture'></a>

## Search Architecture

### 相关页面

相关主题：[MCP Tools and Context Generation](#page-mcp-tools), [Database Schema and Storage](#page-database-schema)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/services/worker/search/SearchOrchestrator.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/search/SearchOrchestrator.ts)
- [src/services/worker/search/strategies/HybridSearchStrategy.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/search/strategies/HybridSearchStrategy.ts)
- [src/services/worker/search/strategies/ChromaSearchStrategy.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/search/strategies/ChromaSearchStrategy.ts)
- [src/services/worker/search/strategies/SQLiteSearchStrategy.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/search/strategies/SQLiteSearchStrategy.ts)
- [src/services/sync/ChromaSync.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/sync/ChromaSync.ts)
- [src/services/sync/ChromaMcpManager.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/sync/ChromaMcpManager.ts)
- [src/services/worker/search/TimelineBuilder.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/worker/search/TimelineBuilder.ts)
</details>

# Search Architecture

## Overview

The Search Architecture in claude-mem provides a multi-strategy search system that enables semantic and structured querying across observations, sessions, and prompts. The architecture employs a plugin-based strategy pattern that allows combining different search backends—primarily Chroma (vector database) and SQLite—through a unified orchestration layer.

The search system serves as the foundation for context injection, enabling Claude Code to retrieve relevant historical observations from previous sessions and maintain knowledge continuity across session boundaries.

---

## Architecture Overview

```mermaid
graph TD
    A[Search Request] --> B[SearchOrchestrator]
    B --> C[HybridSearchStrategy]
    C --> D[ChromaSearchStrategy]
    C --> E[SQLiteSearchStrategy]
    D --> F[ChromaSync]
    F --> G[Chroma DB]
    E --> H[SQLite DB]
    I[ChromaMcpManager] --> G
    J[TimelineBuilder] --> K[Timeline Results]
    
    style B fill:#e1f5fe
    style C fill:#fff3e0
    style D fill:#e8f5e9
    style E fill:#fce4ec
```

---

## Core Components

### SearchOrchestrator

The `SearchOrchestrator` serves as the central entry point for all search operations. It receives search requests, determines which strategies to invoke, and aggregates results from multiple sources.

**Key Responsibilities:**
- Route search requests to appropriate strategies
- Merge and rank results from different backends
- Handle search type filtering (observations, sessions, prompts)
- Support project-scoped searches

**Search Types Supported:**

| Search Type | Description |
|-------------|-------------|
| `all` | Search across observations, sessions, and prompts |
| `observations` | Search observation records only |
| `sessions` | Search session metadata |
| `prompts` | Search user prompts |
| `by-concept` | Find observations tagged with specific concepts |
| `by-file` | Find observations related to specific file paths |
| `by-type` | Filter by observation type (decisions, changes, etc.) |

资料来源：[src/services/worker/search/SearchOrchestrator.ts]()

### HybridSearchStrategy

The `HybridSearchStrategy` combines multiple search strategies to achieve optimal recall and precision. It orchestrates parallel execution of Chroma and SQLite searches, then merges the results.

```mermaid
graph LR
    A[Query] --> B[Chroma Search]
    A --> C[SQLite Search]
    B --> D[Result Merge]
    C --> D
    D --> E[Ranked Results]
```

**Strategy Selection Logic:**
- Vector similarity search → Chroma
- Structured queries (filters, date ranges) → SQLite
- Combined relevance + recency ranking → Hybrid merge

资料来源：[src/services/worker/search/strategies/HybridSearchStrategy.ts]()

### ChromaSearchStrategy

The `ChromaSearchStrategy` implements semantic search using the Chroma vector database. It provides high-dimensional embedding-based similarity search with filtering capabilities.

**Core Features:**
- Batch querying with configurable batch size (`SEARCH_CONSTANTS.CHROMA_BATCH_SIZE`)
- Filter by document type, concepts, file paths
- Ordering by relevance, date descending, or date ascending
- Recency filtering of results

**Key Methods:**
- `executeChromaSearch()` - Performs the actual Chroma query
- `filterByRecency()` - Filters results based on temporal relevance
- `categorizeByDocType()` - Separates results into observations, sessions, prompts

```typescript
const chromaResults = await this.chromaSync.queryChroma(
  query,
  SEARCH_CONSTANTS.CHROMA_BATCH_SIZE,
  whereFilter
);
```

资料来源：[src/services/worker/search/strategies/ChromaSearchStrategy.ts:30-45]()

### SQLiteSearchStrategy

The `SQLiteSearchStrategy` handles structured queries and provides fallback search when Chroma is unavailable. It performs full-text and attribute-based filtering using SQLite's query capabilities.

**Use Cases:**
- Exact match filtering
- Date range queries
- Project-specific searches
- Filtered searches by metadata fields

---

## Vector Search Infrastructure

### ChromaSync

`ChromaSync` manages the synchronization between the local SQLite database and the Chroma vector database. It handles embedding generation and data persistence.

**Responsibilities:**
- Query Chroma collections
- Sync observations to Chroma
- Manage embedding pipelines
- Handle batch operations

资料来源：[src/services/sync/ChromaSync.ts]()

### ChromaMcpManager

`ChromaMcpManager` handles the Model Context Protocol (MCP) integration for Chroma. It provides an abstraction layer for interacting with Chroma's MCP server when available.

**Features:**
- MCP server status monitoring
- Toggle MCP integration on/off
- Graceful fallback when MCP unavailable

资料来源：[src/services/sync/ChromaMcpManager.ts]()

---

## Search Routes API

The search functionality is exposed through HTTP routes managed by the Worker service:

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/search/observations` | GET | Search observations |
| `/search/sessions` | GET | Search sessions |
| `/search/prompts` | GET | Search prompts |
| `/search/by-concept` | GET | Find by concept tag |
| `/search/by-file` | GET | Find by file path |
| `/search/by-type` | GET | Find by observation type |
| `/search/recent-context` | GET | Get recent context |
| `/search/context-timeline` | GET | Get context timeline |
| `/search/timeline-by-query` | GET | Timeline by search query |
| `/context/preview` | GET | Preview context |
| `/context/inject` | POST | Inject context |

资料来源：[src/services/worker/README.md]()

---

## Timeline Search

### TimelineBuilder

`TimelineBuilder` constructs temporal views of search results, enabling users to explore observations and context across time.

**Capabilities:**
- Build timelines based on search queries
- Aggregate results by date periods
- Support context preview generation
- Inject timeline-based context into sessions

```mermaid
graph TD
    A[Search Query] --> B[TimelineBuilder]
    B --> C[Group by Date]
    C --> D[Timeline Nodes]
    D --> E[Context Preview]
    E --> F[Inject to Session]
```

资料来源：[src/services/worker/search/TimelineBuilder.ts]()

---

## Search Configuration

### Configuration Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `CLAUDE_MEM_CONTEXT_OBSERVATIONS` | number | 50 | Observations to inject (1-200) |
| `CLAUDE_MEM_CONTEXT_SESSIONS` | number | varies | Sessions to pull from (1-50) |

### Search Constants

```typescript
const SEARCH_CONSTANTS = {
  CHROMA_BATCH_SIZE: 100,  // Batch size for Chroma queries
  // ... additional constants
};
```

---

## Search Workflow

```mermaid
sequenceDiagram
    participant Client
    participant Orchestrator
    participant HybridStrategy
    participant Chroma
    participant SQLite
    
    Client->>Orchestrator: Search Request
    Orchestrator->>HybridStrategy: Route to Hybrid
    HybridStrategy->>Chroma: Vector Query
    HybridStrategy->>SQLite: Structured Query
    Chroma-->>HybridStrategy: Embedding Results
    SQLite-->>HybridStrategy: Filtered Results
    HybridStrategy->>HybridStrategy: Merge & Rank
    HybridStrategy-->>Orchestrator: Combined Results
    Orchestrator-->>Client: Ranked Results
```

---

## Data Flow

### Observation Search Flow

1. User initiates search via UI or API
2. `SearchOrchestrator` receives and parses request
3. Determines search scope (observations, sessions, prompts)
4. Invokes `HybridSearchStrategy`
5. Parallel execution:
   - `ChromaSearchStrategy` performs vector similarity search
   - `SQLiteSearchStrategy` performs structured filtering
6. Results are categorized by document type
7. Results filtered by recency if configured
8. Final results merged and ranked
9. Returned to client with metadata

### Context Injection Flow

1. User requests context preview or injection
2. `TimelineBuilder` builds temporal view
3. Observations retrieved based on recency and relevance
4. Context formatted for Claude Code consumption
5. Injected into active session via worker service

---

## Strategy Pattern Implementation

The search architecture follows the Strategy pattern, allowing runtime selection of search algorithms:

```mermaid
classDiagram
    class SearchStrategy {
        <<interface>>
        +search(query, options) SearchResult
    }
    
    class HybridSearchStrategy {
        +search(query, options) SearchResult
        -chroma: ChromaSearchStrategy
        -sqlite: SQLiteSearchStrategy
    }
    
    class ChromaSearchStrategy {
        +search(query, options) SearchResult
        -chromaSync: ChromaSync
    }
    
    class SQLiteSearchStrategy {
        +search(query, options) SearchResult
    }
    
    SearchStrategy <|.. HybridSearchStrategy
    SearchStrategy <|.. ChromaSearchStrategy
    SearchStrategy <|.. SQLiteSearchStrategy
```

---

## Error Handling and Fallback

The architecture includes graceful degradation:

1. **Chroma Unavailable**: Falls back to SQLite-only search
2. **MCP Server Down**: Uses direct ChromaSync connection
3. **Empty Results**: Returns partial results from available strategies
4. **Query Parse Error**: Returns structured error with debugging info

---

## Performance Considerations

- **Batch Processing**: Chroma queries use configurable batch sizes
- **Parallel Execution**: Hybrid strategy executes Chroma and SQLite in parallel
- **Recency Filtering**: Reduces result set before expensive merging
- **Lazy Loading**: Large result sets paginated via limit/offset

---

## Related Documentation

- [Worker Service Architecture](src/services/worker/README.md)
- [Context Injection System](#)
- [Observation Data Model](#)

---

<a id='page-mcp-tools'></a>

## MCP Tools and Context Generation

### 相关页面

相关主题：[Search Architecture](#page-search-architecture), [Worker Service Architecture](#page-worker-service)

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

以下源码文件用于生成本页说明：

- [src/server/generation/providers/shared/prompt-builder.ts](https://github.com/thedotmack/claude-mem/blob/main/src/server/generation/providers/shared/prompt-builder.ts)
- [src/sdk/prompts.ts](https://github.com/thedotmack/claude-mem/blob/main/src/sdk/prompts.ts)
- [src/sdk/parser.ts](https://github.com/thedotmack/claude-mem/blob/main/src/sdk/parser.ts)
- [src/services/context-generator.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/context-generator.ts)
- [src/services/smart-file-read/parser.ts](https://github.com/thedotmack/claude-mem/blob/main/src/services/smart-file-read/parser.ts)
- [src/utils/claude-md-utils.ts](https://github.com/thedotmack/claude-mem/blob/main/src/utils/claude-md-utils.ts)
</details>

# MCP Tools and Context Generation

## Overview

MCP (Model Context Protocol) Tools and Context Generation form the core infrastructure that enables claude-mem to provide persistent memory capabilities across Claude Code sessions. This system captures tool usage observations, generates semantic summaries, and makes them available to future sessions through a structured context injection mechanism.

The architecture consists of three primary layers:

1. **Observation Capture Layer** - Captures tool interactions and state changes during Claude Code sessions
2. **Context Generation Layer** - Transforms raw observations into structured, queryable context
3. **Context Injection Layer** - Delivers relevant context to Claude Code when new sessions start

资料来源：[src/server/generation/providers/shared/prompt-builder.ts:1-50]()

---

## Architecture

```mermaid
graph TD
    subgraph "Observation Capture"
        A[Claude Code Session] --> B[Tool Usage Events]
        B --> C[Observation Builder]
        C --> D[Observation XML Format]
    end

    subgraph "Context Generation"
        D --> E[Context Generator Service]
        E --> F[Smart File Parser]
        F --> G[Summary Generator]
        G --> H[Indexed Memory Store]
    end

    subgraph "Context Injection"
        H --> I[MCP Tools]
        H --> J[Search Routes]
        I --> K[Claude Code]
        J --> K
    end

    subgraph "Storage Layer"
        K --> L[~/.claude-mem]
        H --> L
    end
```

---

## Observation System

### XML Schema Structure

Observations are generated in a standardized XML format that allows for structured parsing and searchability. The observation schema includes:

```xml
<observation>
  <type>[ file_read | file_modified | command_executed | error | concept ]</type>
  <title>Brief descriptive title</title>
  <subtitle>Additional context or location</subtitle>
  <facts>
    <fact>Key information point 1</fact>
    <fact>Key information point 2</fact>
  </facts>
  <narrative>Descriptive paragraph of the observation</narrative>
  <concepts>
    <concept>Semantic concept tag</concept>
  </concepts>
  <files_read>
    <file>path/to/file.ext</file>
  </files_read>
  <files_modified>
    <file>path/to/file.ext</file>
  </files_modified>
</observation>
```

资料来源：[src/server/generation/providers/shared/prompt-builder.ts:80-110]()

### Observation Types

The system supports multiple observation types that categorize different types of agent activities:

| Type | Description | Typical Content |
|------|-------------|-----------------|
| `file_read` | File content examination | File paths, content snippets, line numbers |
| `file_modified` | File changes made | Modified files, change descriptions |
| `command_executed` | Terminal command execution | Command, output summary, success/failure |
| `concept` | Conceptual learning | Abstract knowledge, patterns identified |
| `error` | Error conditions | Error messages, recovery actions |

资料来源：[src/sdk/prompts.ts:1-60]()

### Observation Type Configuration

Mode configurations define available observation types through the `ObservationType` interface:

```typescript
interface ObservationType {
  id: string;           // Type identifier (e.g., "file_read")
  label: string;       // Human-readable label
  guidance: string;    // LLM guidance for this type
}
```

The `ModeManager` provides active mode configuration which determines which observation types are available during a session.

资料来源：[src/server/generation/providers/shared/prompt-builder.ts:130-145]()

---

## Prompt Building System

### Primary Prompt Construction

The prompt builder constructs system prompts that instruct Claude Code on how to generate observations. It combines several modular components:

```typescript
function buildObservationPrompt(obs: Observation): string {
  // Parses tool input/output from the observation
  let toolInput: any;
  let toolOutput: any;

  try {
    toolInput = typeof obs.tool_input === 'string' 
      ? JSON.parse(obs.tool_input) 
      : obs.tool_input;
  } catch (error: unknown) {
    logger.debug('SDK', 'Tool input is plain string, using as-is', {
      toolName: obs.tool_name
    });
  }
  // ... continues with XML formatting
}
```

资料来源：[src/sdk/parser.ts:1-40]()

### XML Output Schema Builder

The `buildObservationOutputSchema()` function generates the expected output format for observations:

```typescript
function buildObservationOutputSchema(mode: ModeConfig): string {
  const types = mode.observation_types.map(t => t.id).join(' | ');
  return [
    '<observation>',
    `  <type>[ ${types} ]</type>`,
    '  <title>...</title>',
    '  <subtitle>...</subtitle>',
    '  <facts><fact>...</fact></facts>',
    '  <narrative>...</narrative>',
    '  <concepts><concept>...</concept></concepts>',
    '  <files_read><file>...</file></files_read>',
    '  <files_modified><file>...</file></files_modified>',
    '</observation>',
  ].join('\n');
}
```

资料来源：[src/server/generation/providers/shared/prompt-builder.ts:150-175]()

### Continuation Prompt Building

For multi-turn conversations, continuation prompts maintain context across sessions:

```typescript
export function buildContinuationPrompt(
  userPrompt: string, 
  promptNumber: number, 
  contentSessionId: string, 
  mode: ModeConfig
): string {
  return `${mode.prompts.continuation_greeting}
<observed_from_primary_session>
  <user_request>${userPrompt}</user_request>
  <requested_at>${new Date().toISOString().split('T')[0]}</requested_at>
</observed_from_primary_session>
${mode.prompts.system_identity}
${mode.prompts.observer_role}
${mode.prompts.spatial_awareness}
${mode.prompts.recording_focus}
${mode.prompts.skip_guidance}
${mode.prompts.continuation_instruction}
${mode.prompts.output_format_header}
...
`;
}
```

资料来源：[src/sdk/prompts.ts:80-130]()

---

## Context Generation Service

### Core Responsibilities

The Context Generator Service (`src/services/context-generator.ts`) is responsible for:

1. **Semantic Analysis** - Extracting meaning and relationships from observations
2. **Summary Generation** - Creating condensed summaries of session activities
3. **Concept Extraction** - Identifying and tagging conceptual information
4. **File Reference Tracking** - Maintaining relationships between observations and files

### Smart File Parsing

The smart file parser (`src/services/smart-file-read/parser.ts`) extracts structured information from source files:

```typescript
interface CodeSymbol {
  name: string;
  kind: string;          // function, class, variable, code block, etc.
  signature: string;
  jsdoc?: string;
  lineStart: number;
  lineEnd: number;
  exported: boolean;
  children?: CodeSymbol[];
}
```

资料来源：[src/services/smart-file-read/parser.ts:1-50]()

### Code Symbol Kinds

| Kind | Description | Children Allowed |
|------|-------------|------------------|
| `function` | Function/method definitions | No |
| `class` | Class definitions | Yes |
| `variable` | Variable declarations | No |
| `code` | Code blocks | No |
| `metadata` | Markdown frontmatter | No |
| `reference` | Markdown references | No |

资料来源：[src/services/smart-file-read/parser.ts:30-80]()

### Duplicate Detection

The parser handles duplicate code blocks in markdown files:

```typescript
const codeBlocksByRange = new Map<string, CodeSymbol>();
const duplicateCodeBlocks = new Set<CodeSymbol>();

for (const sym of symbols) {
  if (sym.kind !== "code") continue;
  const rangeKey = `${sym.lineStart}:${sym.lineEnd}`;
  const existing = codeBlocksByRange.get(rangeKey);
  if (existing) {
    if (sym.name !== "anonymous") {
      duplicateCodeBlocks.add(existing);
      codeBlocksByRange.set(rangeKey, sym);
    } else {
      duplicateCodeBlocks.add(sym);
    }
  }
}
```

资料来源：[src/services/smart-file-read/parser.ts:50-80]()

---

## Memory Storage and Retrieval

### Claude-MD Utilities

The `claude-md-utils.ts` module handles writing observations to `.claude.md` files in project directories:

```typescript
export function writeClaudeMdToFolder(
  folderPath: string, 
  newContent: string, 
  targetFilename?: string
): void {
  const resolvedPath = path.resolve(folderPath);

  // Security: Skip .git directories
  if (resolvedPath.includes('/.git/') || 
      resolvedPath.includes('\\.git\\') || 
      resolvedPath.endsWith('/.git') || 
      resolvedPath.endsWith('\\.git')) return;

  const filename = targetFilename ?? getTargetFilename();
  const claudeMdPath = path.join(folderPath, filename);
  // ... write and atomic replace
}
```

资料来源：[src/utils/claude-md-utils.ts:1-60]()

### Tagged Content Replacement

Observations are stored using tagged content markers to enable later updates:

```typescript
function replaceTaggedContent(
  existingContent: string, 
  newContent: string
): string {
  const startTag = getStartTag();
  const endTag = getEndTag();
  
  // Replaces content between tags or appends
  return existingContent.substring(0, startIdx) +
    `${startTag}\n${newContent}\n${endTag}` +
    existingContent.substring(endIdx + endTag.length);
}
```

### Timeline Formatting

For human-readable output in `.claude.md` files:

```typescript
interface ParsedObservation {
  id: string;
  time: string;
  typeEmoji: string;
  title: string;
  tokens: string;
  epoch: number; 
}

export function formatTimelineForClaudeMd(timelineText: string): string {
  const lines: string[] = [];
  lines.push('# Recent Activity');
  // ... formatting logic
}
```

资料来源：[src/utils/claude-md-utils.ts:80-120]()

---

## Summary Generation

### Summary Schema

Summaries provide condensed context for quick retrieval:

```xml
<summary>
  <request>Original user request or goal</request>
  <investigated>Files and areas explored</investigated>
  <learned>Key findings and decisions made</learned>
  <completed>Tasks accomplished</completed>
  <next_steps>Suggested follow-up actions</next_steps>
  <notes>Additional context</notes>
</summary>
```

### Summary Prompt Building

The summary builder uses a dedicated prompt format:

```typescript
`${mode.prompts.summary_context_label}
${lastAssistantMessage}
${mode.prompts.summary_format_instruction}
<summary>
  <request>${mode.prompts.xml_summary_request_placeholder}</request>
  <investigated>${mode.prompts.xml_summary_investigated_placeholder}</investigated>
  <learned>${mode.prompts.xml_summary_learned_placeholder}</learned>
  <completed>${mode.prompts.xml_summary_completed_placeholder}</completed>
  <next_steps>${mode.prompts.xml_summary_next_steps_placeholder}</next_steps>
  <notes>${mode.prompts.xml_summary_notes_placeholder}</notes>
</summary>
REMINDER: Your response MUST use <summary> as the root tag, NOT <observation>.
${mode.prompts.summary_footer}`;
```

资料来源：[src/sdk/prompts.ts:40-80]()

---

## Configuration Parameters

### Context Settings Modal

The UI provides configuration options for context injection:

| Parameter | Default | Range | Description |
|-----------|---------|-------|-------------|
| `CLAUDE_MEM_CONTEXT_OBSERVATIONS` | 50 | 1-200 | Number of recent observations to include |
| `CLAUDE_MEM_CONTEXT_SESSIONS` | varies | 1-50 | Number of recent sessions to pull from |
| `CLAUDE_MEM_WORKER_PORT` | 37777 | - | Worker service port |
| `RAGTIME_TRANSCRIPT_MAX_AGE` | 24 | hours | Max age of transcripts to keep |
| `RAGTIME_FILE_LIMIT` | 0 | - | Limit files to process (0=all) |

资料来源：[src/ui/viewer/components/ContextSettingsModal.tsx:1-60]()

---

## XML Escaping

All user-generated content is properly escaped before inclusion in XML output:

```typescript
function escapeXml(text: string): string {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}
```

资料来源：[src/server/generation/providers/shared/prompt-builder.ts:180-195]()

---

## Workflow Summary

```mermaid
graph LR
    A[User Prompt] --> B[Claude Code]
    B --> C[Tool Execution]
    C --> D[MCP Tools Capture]
    D --> E[Observation XML]
    E --> F[Context Generator]
    F --> G[Summary Generator]
    G --> H[Memory Store]
    
    I[New Session] --> J[Search Routes]
    J --> K[Context Generator]
    K --> L[Relevant Context]
    L --> M[Claude Code]
```

### Step-by-Step Flow

1. **Capture Phase**: Claude Code executes tools; MCP tools capture observations
2. **Parse Phase**: Raw tool input/output is parsed into structured formats
3. **Generate Phase**: Context generator creates observations and summaries
4. **Store Phase**: Observations are indexed and stored in `~/.claude-mem`
5. **Inject Phase**: New sessions query relevant context via Search Routes
6. **Resume Phase**: Claude Code receives context and continues with project memory

---

## Key Source Files Reference

| File | Purpose |
|------|---------|
| `src/server/generation/providers/shared/prompt-builder.ts` | Core prompt construction and XML schema |
| `src/sdk/prompts.ts` | SDK-side prompt building functions |
| `src/sdk/parser.ts` | Observation parsing from tool outputs |
| `src/services/context-generator.ts` | Context generation orchestration |
| `src/services/smart-file-read/parser.ts` | Source code symbol extraction |
| `src/utils/claude-md-utils.ts` | File-based memory persistence |
| `src/ui/viewer/components/ContextSettingsModal.tsx` | Context configuration UI |

---

## Summary

MCP Tools and Context Generation form the brain of claude-mem's persistent memory system. By capturing tool interactions as structured XML observations, generating semantic summaries, and providing queryable context to new sessions, claude-mem enables Claude Code to maintain continuity of knowledge about projects even after sessions end. The system is highly configurable through mode settings and context parameters, and stores all data locally in `~/.claude-mem` for privacy and portability.

---

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

## Installation Guide

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/npx-cli/commands/install.ts](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/commands/install.ts)
- [src/npx-cli/install/setup-runtime.ts](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/install/setup-runtime.ts)
- [openclaw/install.sh](https://github.com/thedotmack/claude-mem/blob/main/openclaw/install.sh)
- [openclaw/openclaw.plugin.json](https://github.com/thedotmack/claude-mem/blob/main/openclaw/openclaw.plugin.json)
- [docker/claude-mem/Dockerfile](https://github.com/thedotmack/claude-mem/blob/main/docker/claude-mem/Dockerfile)
- [docker/claude-mem/README.md](https://github.com/thedotmack/claude-mem/blob/main/docker/claude-mem/README.md)
</details>

# Installation Guide

Claude-Mem is a persistent memory plugin for Claude Code, enabling seamless context preservation across sessions. This guide covers all supported installation methods across different platforms and integrated development environments.

## Overview

Claude-Mem can be installed through multiple channels depending on your use case:

| Installation Method | Platform | Use Case |
|-------------------|----------|----------|
| `npx claude-mem install` | macOS, Linux, Windows | Standard installation for Claude Code |
| `npx claude-mem install --ide gemini-cli` | All platforms | Integration with Gemini CLI |
| `npx claude-mem install --ide opencode` | All platforms | Integration with OpenCode |
| `/plugin` commands | Claude Code | In-app plugin marketplace |
| OpenClaw Gateway | OpenClaw | Persistent memory on OpenClaw gateways |
| Docker | Containerized | Isolated deployment environments |

All installations store data locally in `~/.claude-mem` on the host machine. 资料来源：[README.md](https://github.com/thedotmack/claude-mem/blob/main/README.md)

## System Requirements

Before installation, ensure your environment meets the following prerequisites:

| Requirement | Specification |
|-------------|---------------|
| Node.js | 18+ |
| Package Manager | npm, npx |
| Claude Code | Pro/Max subscription for CLI-based auth |
| API Key | `ANTHROPIC_API_KEY` (optional alternative) |

For API-based authentication in CI/CD environments, set the `ANTHROPIC_API_KEY` environment variable. Claude Code installations with authenticated Pro/Max subscriptions automatically use built-in authentication. 资料来源：[README.md](https://github.com/thedotmack/claude-mem/blob/main/README.md)

## Standard Installation (Claude Code)

### Quick Install

The recommended installation method uses npx to install and configure the plugin:

```bash
npx claude-mem install
```

This command performs the following operations:

1. Detects the Claude Code installation location
2. Installs plugin hooks in the appropriate configuration directory
3. Sets up the worker service for observation capture
4. Configures the local memory storage at `~/.claude-mem`

### Post-Installation Steps

After installation completes:

1. Keep the provided localhost URL open in a browser
2. Open Claude Code in any project
3. Observations stream automatically as Claude reads, edits, and runs commands
4. Memory injection starts on your second session in a project

Two paths are available for building memory:

| Option | Approach | Time |
|--------|----------|------|
| A. Passive | Just start working; memory builds from your first prompt | Ongoing |
| B. Front-load | Run `/learn-codebase` to ingest the entire repository | ~5 minutes |

资料来源：[src/npx-cli/commands/install.ts](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/commands/install.ts)

## IDE-Specific Installations

### Gemini CLI

```bash
npx claude-mem install --ide gemini-cli
```

This auto-detects the `~/.gemini` configuration directory and installs the appropriate hooks for Gemini CLI integration.

### OpenCode

```bash
npx claude-mem install --ide opencode
```

Configures hooks specifically for OpenCode IDE environments.

资料来源：[src/npx-cli/install/setup-runtime.ts](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/install/setup-runtime.ts)

## In-App Plugin Installation

For users who prefer the Claude Code interface:

1. Open Claude Code and access the plugin marketplace
2. Add the plugin: `/plugin marketplace add thedotmack/claude-mem`
3. Install the plugin: `/plugin install claude-mem`
4. Restart Claude Code or Gemini CLI

Context from previous sessions automatically appears in new sessions after installation completes. 资料来源：[README.md](https://github.com/thedotmack/claude-mem/blob/main/README.md)

## OpenClaw Gateway Installation

For persistent memory on OpenClaw gateways, a dedicated installation script is provided:

```bash
curl -fsSL https://install.cmem.ai/openclaw.sh | bash
```

This script configures claude-mem as a persistent memory plugin on OpenClaw gateways. 资料来源：[openclaw/install.sh](https://github.com/thedotmack/claude-mem/blob/main/openclaw/install.sh)

### OpenClaw Plugin Configuration

The OpenClaw integration uses a plugin manifest file that defines:

```json
{
  "name": "claude-mem",
  "version": "1.0.0",
  "description": "Persistent memory for Claude Code"
}
```

资料来源：[openclaw/openclaw.plugin.json](https://github.com/thedotmack/claude-mem/blob/main/openclaw/openclaw.plugin.json)

## Docker Installation

For containerized or isolated deployment environments, Docker installation is available.

### Building the Docker Image

```bash
cd docker/claude-mem
docker build -t claude-mem .
```

### Running the Container

```bash
docker run -d \
  --name claude-mem \
  -p 8080:8080 \
  -v ~/.claude-mem:/data \
  claude-mem
```

The Docker setup uses a multi-stage build with Node.js 20 as the base image and serves the worker service on port 8080. 资料来源：[docker/claude-mem/Dockerfile](https://github.com/thedotmack/claude-mem/blob/main/docker/claude-mem/Dockerfile)

### Docker Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `PORT` | Worker service port | `8080` |
| `CLAUDE_MEM_DATA_DIR` | Memory storage directory | `/data` |
| `ANTHROPIC_API_KEY` | API authentication | Required if no Claude Code |

资料来源：[docker/claude-mem/README.md](https://github.com/thedotmack/claude-mem/blob/main/docker/claude-mem/README.md)

## Installation Workflow

```mermaid
graph TD
    A[User runs npx claude-mem install] --> B{Detect Platform}
    B -->|macOS/Linux| C[Find Claude Code config]
    B -->|Windows| D[Find Claude Code config]
    B -->|Gemini CLI| E[Detect ~/.gemini]
    B -->|OpenCode| F[Detect OpenCode config]
    
    C --> G[Install hooks to config dir]
    D --> G
    E --> H[Install gemini-cli hooks]
    F --> I[Install opencode hooks]
    
    G --> J[Start worker service]
    H --> J
    I --> J
    
    J --> K[Display success URL]
    K --> L[User opens Claude Code]
    L --> M[Observations begin streaming]
    M --> N[Memory injection on 2nd session]
```

## Verification and Status

After installation, verify the setup:

```bash
npx claude-mem status
```

If the worker is not yet ready:

```bash
npx claude-mem start
```

Manual startup may be required if the worker failed to start automatically on the configured port (default: 8080). 资料来源：[src/npx-cli/commands/install.ts](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/commands/install.ts)

## Uninstallation

To uninstall claude-mem:

1. Close all Claude Code sessions (prevents hooks from recreating configuration)
2. Run the uninstall command or manually remove:
   - `~/.claude-mem` directory
   - Plugin hooks from Claude Code config directory
   - Any installed Claude Code plugins

资料来源：[src/npx-cli/commands/install.ts](https://github.com/thedotmack/claude-mem/blob/main/src/npx-cli/commands/install.ts)

## Troubleshooting

| Issue | Solution |
|-------|----------|
| Worker not ready | Wait ~30 seconds, then run `npx claude-mem start` |
| Hooks recreated | Close all Claude Code sessions before uninstalling |
| No observations | Ensure memory injection starts on second session |
| Auth issues | Verify `ANTHROPIC_API_KEY` or Claude Code Pro/Max subscription |

### First Session Hint

The welcome hint on first sessions can be disabled:

```bash
CLAUDE_MEM_WELCOME_HINT_ENABLED=false
```

### Documentation

For additional help:

- Documentation: https://docs.claude-mem.ai
- How it works: `/how-it-works` in Claude Code

---

---

## Doramagic 踩坑日志

项目：thedotmack/claude-mem

摘要：发现 39 个潜在踩坑项，其中 13 个为 high/blocking；最高优先级：安装坑 - 来源证据：Windows worker spawn silently fails when user home path contains a space (four stacked bugs, still present in v13.2.0)。

## 1. 安装坑 · 来源证据：Windows worker spawn silently fails when user home path contains a space (four stacked bugs, still present in v13.2.0)

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Windows worker spawn silently fails when user home path contains a space (four stacked bugs, still present in v13.2.0)
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_24ed2d144536406bb1235c9249013f81 | https://github.com/thedotmack/claude-mem/issues/2521 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。

## 2. 安装坑 · 来源证据：Windows: cmd.exe /c uvx wrapper breaks Chroma MCP stdio on WinGet uv installs (regression after #1190 / #1199) --> FIX…

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Windows: cmd.exe /c uvx wrapper breaks Chroma MCP stdio on WinGet uv installs (regression after #1190 / #1199) --> FIX attacched
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_a6c844000d9b4adead4a2fdb73660c8d | https://github.com/thedotmack/claude-mem/issues/2426 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 3. 安装坑 · 来源证据：Worker PID file not cleaned up after system sleep/hibernate, Worker fails to restart on new session

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Worker PID file not cleaned up after system sleep/hibernate, Worker fails to restart on new session
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_2a88889db8f4416a9daf23d9979fee71 | https://github.com/thedotmack/claude-mem/issues/2432 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 4. 安装坑 · 来源证据：chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_e1a68c6d9a77481897440b34fca959e4 | https://github.com/thedotmack/claude-mem/issues/2438 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 5. 安装坑 · 来源证据：v13.0.0 marketplace install bundle ships without bundled node_modules (zod, shell-quote)

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v13.0.0 marketplace install bundle ships without bundled node_modules (zod, shell-quote)
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_13c1450c63bb4900bed699a4f9b2abb2 | https://github.com/thedotmack/claude-mem/issues/2407 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 6. 安装坑 · 来源证据：v13.2.0: smart_outline / smart_unfold / smart_search silently no-op — tree-sitter grammars unresolvable due to missing…

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v13.2.0: smart_outline / smart_unfold / smart_search silently no-op — tree-sitter grammars unresolvable due to missing node_modules (Linux)
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_d56c3d9492594acab8d0bb29a46a6fee | https://github.com/thedotmack/claude-mem/issues/2520 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 7. 安装坑 · 来源证据：v13: merged_into_project migration silently skipped on pre-existing DBs (schema_versions ≤ 23)

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v13: merged_into_project migration silently skipped on pre-existing DBs (schema_versions ≤ 23)
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_510ecb03a1de412f940987e370c68fac | https://github.com/thedotmack/claude-mem/issues/2433 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 8. 配置坑 · 来源证据：Use node to run mcp for windows environment

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Use node to run mcp for windows environment
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_95d37c5d34a749f7a25fdd5fe1dc7969 | https://github.com/thedotmack/claude-mem/issues/2446 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 9. 配置坑 · 来源证据：chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_77fdc7c371f042eeb70fbeb52a7a2788 | https://github.com/thedotmack/claude-mem/issues/2438 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 10. 运行坑 · 来源证据：自动运行时突然报下图所示内容，然后插件就不能用了

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：自动运行时突然报下图所示内容，然后插件就不能用了
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_2d5aa43a4c5a4e46a0f2122dea46947a | https://github.com/thedotmack/claude-mem/issues/2441 | 来源类型 github_issue 暴露的待验证使用条件。

## 11. 安全/权限坑 · 来源证据：Feature: Vertex AI support for Gemini provider

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature: Vertex AI support for Gemini provider
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_77bf4085ec9e46c59fdaffa4ad889dcc | https://github.com/thedotmack/claude-mem/issues/2522 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。

## 12. 安全/权限坑 · 来源证据：Windows: chroma-mcp connection fails instantly — cmd.exe interprets < > in version constraints as redirection

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Windows: chroma-mcp connection fails instantly — cmd.exe interprets < > in version constraints as redirection
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_f38d625f3d834e7d8179d4a3176f3a73 | https://github.com/thedotmack/claude-mem/issues/2509 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 13. 安全/权限坑 · 来源证据：v13.2.0: observer SDK responses dropped by parser as non-XML; observations table stays at 0

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v13.2.0: observer SDK responses dropped by parser as non-XML; observations table stays at 0
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_fbb9eadf507d4876b859b92bd87d2ab2 | https://github.com/thedotmack/claude-mem/issues/2485 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 14. 安装坑 · 失败模式：installation: OpenClaw installer fails with TypeScript build error on Linux

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: OpenClaw installer fails with TypeScript build error on Linux
- 对用户的影响：Developers may fail before the first successful local run: OpenClaw installer fails with TypeScript build error on Linux
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: OpenClaw installer fails with TypeScript build error on Linux. Context: Observed when using node, linux
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_f6c0a0d684fa5f1135ac669cd98df70e | https://github.com/thedotmack/claude-mem/issues/2530 | OpenClaw installer fails with TypeScript build error on Linux

## 15. 安装坑 · 失败模式：installation: Windows worker spawn silently fails when user home path contains a space (four stacked bugs,...

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: Windows worker spawn silently fails when user home path contains a space (four stacked bugs, still present in v13.2.0)
- 对用户的影响：Developers may fail before the first successful local run: Windows worker spawn silently fails when user home path contains a space (four stacked bugs, still present in v13.2.0)
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Windows worker spawn silently fails when user home path contains a space (four stacked bugs, still present in v13.2.0). Context: Observed when using windows
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_0190fe2b64cffaffac244e9ef7033f4e | https://github.com/thedotmack/claude-mem/issues/2521 | Windows worker spawn silently fails when user home path contains a space (four stacked bugs, still present in v13.2.0)

## 16. 安装坑 · 失败模式：installation: Worker PID file not cleaned up after system sleep/hibernate, Worker fails to restart on new s...

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: Worker PID file not cleaned up after system sleep/hibernate, Worker fails to restart on new session
- 对用户的影响：Developers may fail before the first successful local run: Worker PID file not cleaned up after system sleep/hibernate, Worker fails to restart on new session
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Worker PID file not cleaned up after system sleep/hibernate, Worker fails to restart on new session. Context: Observed when using node, windows
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_967ff316b7cd3cebcc05db7b0d3c8d9d | https://github.com/thedotmack/claude-mem/issues/2432 | Worker PID file not cleaned up after system sleep/hibernate, Worker fails to restart on new session

## 17. 安装坑 · 失败模式：installation: [Bug] 13.x worker fails with "Cannot find module 'zod/v3'" — package-lock.json missing zod entry

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: [Bug] 13.x worker fails with "Cannot find module 'zod/v3'" — package-lock.json missing zod entry
- 对用户的影响：Developers may fail before the first successful local run: [Bug] 13.x worker fails with "Cannot find module 'zod/v3'" — package-lock.json missing zod entry
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug] 13.x worker fails with "Cannot find module 'zod/v3'" — package-lock.json missing zod entry. Context: Observed when using node, python, macos, linux
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_577adec48438b667deb5de48f5dca7f0 | https://github.com/thedotmack/claude-mem/issues/2437 | [Bug] 13.x worker fails with "Cannot find module 'zod/v3'" — package-lock.json missing zod entry

## 18. 安装坑 · 失败模式：installation: [Windows] bun-runner.js spawn EPERM when antivirus (360/Defender) blocks cmd → bun.cmd chain

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: [Windows] bun-runner.js spawn EPERM when antivirus (360/Defender) blocks cmd → bun.cmd chain
- 对用户的影响：Developers may fail before the first successful local run: [Windows] bun-runner.js spawn EPERM when antivirus (360/Defender) blocks cmd → bun.cmd chain
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Windows] bun-runner.js spawn EPERM when antivirus (360/Defender) blocks cmd → bun.cmd chain. Context: Observed when using node, windows
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_4f334c0890e60adcd2706806e12f126c | https://github.com/thedotmack/claude-mem/issues/2528 | [Windows] bun-runner.js spawn EPERM when antivirus (360/Defender) blocks cmd → bun.cmd chain

## 19. 安装坑 · 失败模式：installation: [feat] Option to load only memory-related skills

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: [feat] Option to load only memory-related skills
- 对用户的影响：Developers may fail before the first successful local run: [feat] Option to load only memory-related skills
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [feat] Option to load only memory-related skills. Context: Observed during installation or first-run setup.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_838f002b6acafaa53828fd03d9450ed6 | https://github.com/thedotmack/claude-mem/issues/2448 | [feat] Option to load only memory-related skills

## 20. 安装坑 · 失败模式：installation: chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection
- 对用户的影响：Developers may fail before the first successful local run: chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection. Context: Observed when using python, windows
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_9195685a79daaf4720e0243904f7946d | https://github.com/thedotmack/claude-mem/issues/2438 | chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection

## 21. 安装坑 · 失败模式：installation: claude-mem v13.2.0: transcript-watcher.cjs missing from NPM bundle

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: claude-mem v13.2.0: transcript-watcher.cjs missing from NPM bundle
- 对用户的影响：Developers may fail before the first successful local run: claude-mem v13.2.0: transcript-watcher.cjs missing from NPM bundle
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: claude-mem v13.2.0: transcript-watcher.cjs missing from NPM bundle. Context: Observed when using node, python, linux
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_a54bc450a4d11e378deac2c0452f8c0f | https://github.com/thedotmack/claude-mem/issues/2450 | claude-mem v13.2.0: transcript-watcher.cjs missing from NPM bundle

## 22. 安装坑 · 失败模式：installation: v13.0.0 marketplace install bundle ships without bundled node_modules (zod, shell-quote)

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v13.0.0 marketplace install bundle ships without bundled node_modules (zod, shell-quote)
- 对用户的影响：Developers may fail before the first successful local run: v13.0.0 marketplace install bundle ships without bundled node_modules (zod, shell-quote)
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v13.0.0 marketplace install bundle ships without bundled node_modules (zod, shell-quote). Context: Observed when using node, windows
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_910a8a9b41ad8e6e15c1867e5ad4f96c | https://github.com/thedotmack/claude-mem/issues/2407 | v13.0.0 marketplace install bundle ships without bundled node_modules (zod, shell-quote)

## 23. 安装坑 · 失败模式：installation: v13.2.0: observer SDK responses dropped by parser as non-XML; observations table stays at 0

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v13.2.0: observer SDK responses dropped by parser as non-XML; observations table stays at 0
- 对用户的影响：Developers may fail before the first successful local run: v13.2.0: observer SDK responses dropped by parser as non-XML; observations table stays at 0
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v13.2.0: observer SDK responses dropped by parser as non-XML; observations table stays at 0. Context: Observed when using node, python, macos
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_32ef30e0e80f6e41f6f07078c0659311 | https://github.com/thedotmack/claude-mem/issues/2485 | v13.2.0: observer SDK responses dropped by parser as non-XML; observations table stays at 0

## 24. 安装坑 · 失败模式：installation: v13.2.0: smart_outline / smart_unfold / smart_search silently no-op — tree-sitter grammars un...

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v13.2.0: smart_outline / smart_unfold / smart_search silently no-op — tree-sitter grammars unresolvable due to missing node_modules (Linux)
- 对用户的影响：Developers may fail before the first successful local run: v13.2.0: smart_outline / smart_unfold / smart_search silently no-op — tree-sitter grammars unresolvable due to missing node_modules (Linux)
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v13.2.0: smart_outline / smart_unfold / smart_search silently no-op — tree-sitter grammars unresolvable due to missing node_modules (Linux). Context: Observed when using node, python, linux
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_25d358b5f6dfe891ef20a29ba6e827dc | https://github.com/thedotmack/claude-mem/issues/2520 | v13.2.0: smart_outline / smart_unfold / smart_search silently no-op — tree-sitter grammars unresolvable due to missing node_modules (Linux)

## 25. 安装坑 · 失败模式：installation: v13.x: observations never persisted — hooks reach worker, pending_messages stays empty, sdk_s...

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v13.x: observations never persisted — hooks reach worker, pending_messages stays empty, sdk_sessions.memory_session_id never populated
- 对用户的影响：Developers may fail before the first successful local run: v13.x: observations never persisted — hooks reach worker, pending_messages stays empty, sdk_sessions.memory_session_id never populated
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v13.x: observations never persisted — hooks reach worker, pending_messages stays empty, sdk_sessions.memory_session_id never populated. Context: Observed when using python, macos
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_62407cc74d1dc4a1fbebe438679ae0be | https://github.com/thedotmack/claude-mem/issues/2533 | v13.x: observations never persisted — hooks reach worker, pending_messages stays empty, sdk_sessions.memory_session_id never populated

## 26. 安装坑 · 来源证据：Codex CLI: PreToolUse hook returned unsupported suppressOutput

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Codex CLI: PreToolUse hook returned unsupported suppressOutput
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_9022a732f6e54ba39309c5377cf2d8fa | https://github.com/thedotmack/claude-mem/issues/2360 | 来源类型 github_issue 暴露的待验证使用条件。

## 27. 安装坑 · 来源证据：[feat] Option to load only memory-related skills

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[feat] Option to load only memory-related skills
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_efa30fc4873343aea26f804c8d1113ec | https://github.com/thedotmack/claude-mem/issues/2448 | 来源类型 github_issue 暴露的待验证使用条件。

## 28. 配置坑 · 可能修改宿主 AI 配置

- 严重度：medium
- 证据强度：source_linked
- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。
- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。
- 证据：capability.host_targets | github_repo:1048065319 | https://github.com/thedotmack/claude-mem | host_targets=claude, claude_code

## 29. 配置坑 · 失败模式：configuration: Feature: Vertex AI support for Gemini provider

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Feature: Vertex AI support for Gemini provider
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Feature: Vertex AI support for Gemini provider
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Feature: Vertex AI support for Gemini provider. Context: Observed during installation or first-run setup.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_d3519e41cb7b1df860b0a5e6ae7db82e | https://github.com/thedotmack/claude-mem/issues/2522 | Feature: Vertex AI support for Gemini provider

## 30. 配置坑 · 失败模式：configuration: Use node to run mcp for windows environment

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Use node to run mcp for windows environment
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Use node to run mcp for windows environment
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Use node to run mcp for windows environment. Context: Observed when using node, windows, macos, linux
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_7e6bf076e8e465cee8256dd4cb41c3d4 | https://github.com/thedotmack/claude-mem/issues/2446 | Use node to run mcp for windows environment

## 31. 配置坑 · 失败模式：configuration: Windows: chroma-mcp connection fails instantly — cmd.exe interprets < > in version constraint...

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Windows: chroma-mcp connection fails instantly — cmd.exe interprets < > in version constraints as redirection
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Windows: chroma-mcp connection fails instantly — cmd.exe interprets < > in version constraints as redirection
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Windows: chroma-mcp connection fails instantly — cmd.exe interprets < > in version constraints as redirection. Context: Observed when using node, python, windows
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_e40a2ed6db40844214cbb7d7c39088e4 | https://github.com/thedotmack/claude-mem/issues/2509 | Windows: chroma-mcp connection fails instantly — cmd.exe interprets < > in version constraints as redirection

## 32. 配置坑 · 失败模式：configuration: [Windows] chroma-mcp fails to start — '>' and '<' in version constraints interpreted as cmd.e...

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: [Windows] chroma-mcp fails to start — '>' and '<' in version constraints interpreted as cmd.exe redirects
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Windows] chroma-mcp fails to start — '>' and '<' in version constraints interpreted as cmd.exe redirects
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Windows] chroma-mcp fails to start — '>' and '<' in version constraints interpreted as cmd.exe redirects. Context: Observed when using node, python, windows
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_b7f38212a7bbb06091eda408d7b08fbb | https://github.com/thedotmack/claude-mem/issues/2529 | [Windows] chroma-mcp fails to start — '>' and '<' in version constraints interpreted as cmd.exe redirects

## 33. 配置坑 · 来源证据：Native Azure AI Foundry support (ANTHROPIC_FOUNDRY_* env vars)

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Native Azure AI Foundry support (ANTHROPIC_FOUNDRY_* env vars)
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_b7808109101d47ccb8519f238757da11 | https://github.com/thedotmack/claude-mem/issues/2524 | 来源类型 github_issue 暴露的待验证使用条件。

## 34. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:1048065319 | https://github.com/thedotmack/claude-mem | README/documentation is current enough for a first validation pass.

## 35. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:1048065319 | https://github.com/thedotmack/claude-mem | last_activity_observed missing

## 36. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:1048065319 | https://github.com/thedotmack/claude-mem | no_demo; severity=medium

## 37. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:1048065319 | https://github.com/thedotmack/claude-mem | no_demo; severity=medium

## 38. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:1048065319 | https://github.com/thedotmack/claude-mem | issue_or_pr_quality=unknown

## 39. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:1048065319 | https://github.com/thedotmack/claude-mem | release_recency=unknown

<!-- canonical_name: thedotmack/claude-mem; human_manual_source: deepwiki_human_wiki -->
