team-memory-hub 1.6.0
Team Memory Hub - AI context memory management and distribution system
License: MIT
Requires Python: >=3.11
Keywords: ai, context, fastapi, knowledge-base, mcp, memory, team

# Team Memory Hub (TMH)

AI 上下文记忆管理与分发系统 | AI Context Memory Management & Distribution System

---

## 简介 | Introduction

**Team Memory Hub** 是一个面向 AI 辅助开发团队的集体记忆管理系统。它帮助团队积累、组织、检索和分发项目经验、架构决策、编码规范等知识，让 AI 助手能够基于团队积累的上下文提供更精准的协助。

**Team Memory Hub** is a collective memory management system for AI-assisted development teams. It helps teams accumulate, organize, retrieve, and distribute project experiences, architectural decisions, coding standards, and other knowledge, enabling AI assistants to provide more accurate assistance based on accumulated team context.

---

## 核心特性 | Key Features

| 特性 Feature | 描述 Description |
|---|---|
| **双引擎存储** Dual-Engine Storage | SQLite 索引 + 文件系统原文，兼顾查询性能与内容完整性 |
| **混合搜索** Hybrid Search | BM25 关键词 + 向量语义搜索，Score Fusion 融合排序 |
| **三层 Context** Three-Layer Context | L0 核心规范 → L1 项目上下文 → L2 按需搜索 |
| **三层上传** Three-Tier Upload | Hook 零 token → Script ~100 token → MCP ~200 token |
| **MCP Server** | 5 个工具（全 CRUD），tool_set 配置（read_only/read_write/full_crud） |
| **记忆整合** Memory Consolidation | 语义聚类 → LLM 合并建议 → 人工确认 |
| **自动维护** Auto Curation | 11 项自动维护任务（去重、过时检测、归档、完整性校验等） |
| **质量生命周期** Quality Lifecycle | community → verified → pinned / stale → archived |
| **RBAC 权限** | admin > maintainer > member > viewer，细粒度权限覆盖 |
| **双重认证** Dual Auth | JWT + API Key（5 种 scope） |
| **SSE 实时事件** Real-time Events | 8 种事件类型，按团队/类型过滤 |
| **Web Dashboard** | Jinja2 + HTMX 动态交互，管理后台 + 搜索调试 |
| **CLI 工具** | `tmh` 全局命令，覆盖所有核心操作 |

---

## 技术栈 | Tech Stack

| 组件 Component | 技术 Technology |
|---|---|
| 后端 Backend | Python 3.11+, FastAPI, Uvicorn |
| 数据库 Database | SQLite (WAL) + aiosqlite + FTS5 + sqlite-vec |
| 数据模型 Models | Pydantic v2 |
| 认证 Auth | JWT (python-jose) + API Keys (bcrypt) |
| 前端 Dashboard | Jinja2 + HTMX + Pico CSS + Chart.js |
| 嵌入 Embedding | OpenAI / Gemini / ONNX 本地 / OpenAI-compatible (Ollama/vLLM) |
| LLM | Claude (anthropic) / Gemini / Rules Engine (无 LLM 降级) |

---

## 安装 | Installation

### 方式一：pip 安装（推荐）| Option 1: pip install (recommended)

```bash
git clone <repo-url>
cd team-memory-hub

# 基础安装 | Basic install
pip install -e .

# 含 embedding 支持 | With embedding support
pip install -e ".[embedding]"

# 含 LLM 支持 | With LLM support
pip install -e ".[llm]"

# 全功能安装 | Full install
pip install -e ".[all]"

# 开发环境 | Development
pip install -e ".[dev]"
```

安装后 `tmh` 命令全局可用：

After installation, the `tmh` command is globally available:

```bash
tmh --help
```

### 方式二：Docker 部署 | Option 2: Docker Deployment

```bash
# 复制配置 | Copy config
cp .env.example .env
# 编辑 .env 设置 TMH_JWT_SECRET | Edit .env to set TMH_JWT_SECRET

# 启动 TMH + Ollama | Start TMH + Ollama
docker-compose up -d

# 服务地址 | Service URLs:
# API:       http://localhost:8000
# Dashboard: http://localhost:8000/dashboard/
# API Docs:  http://localhost:8000/docs
# Ollama:    http://localhost:11434
```

---

## 配置 | Configuration

TMH 使用 `tmh.toml` 配置文件，环境变量可覆盖任意配置项。

TMH uses `tmh.toml` for configuration. Environment variables override any config value.

### 最小配置 | Minimal Configuration

```toml
[server]
host = "0.0.0.0"
port = 8000
data_dir = "./data"

[auth]
jwt_secret = "your-secret-key"  # 必须修改 | Must change

[database]
path = "./data/team_memory.db"
```

### 完整配置 | Full Configuration

```toml
[server]
host = "0.0.0.0"
port = 8000
debug = false
data_dir = "./data"
cors_origins = ["http://localhost:3000"]

[auth]
jwt_secret = "CHANGE-ME-IN-PRODUCTION"
jwt_algorithm = "HS256"
access_token_expire_minutes = 15
refresh_token_expire_days = 30

[database]
path = "./data/team_memory.db"
wal_mode = true
busy_timeout_ms = 10000

[storage]
memories_dir = "./data/memories"
specs_dir = "./data/specs"
chats_dir = "./data/chats"

[write_queue]
batch_timeout_ms = 100
batch_max_size = 50

[search]
engine = "hybrid"           # hybrid | keyword_only | vector_only
semantic_weight = 0.7
keyword_weight = 0.3
candidate_multiplier = 3
score_normalization = "min_max"

[embedding]
provider = "openai_compatible"  # openai_compatible | openai | gemini | onnx
dimensions = 384

[embedding.openai_compatible]
base_url = "http://localhost:11434"
model = "nomic-embed-text"
api_key = ""

[consolidation]
enabled = true
scan_schedule = "0 4 * * *"
scan_days = 30
cluster_threshold = 0.85
max_suggestions_per_scan = 20

[logging]
level = "INFO"
format = "json"
```

### 环境变量 | Environment Variables

| 环境变量 Variable | 说明 Description | 默认值 Default |
|---|---|---|
| `TMH_SERVER_HOST` | 绑定地址 | `0.0.0.0` |
| `TMH_SERVER_PORT` | 监听端口 | `8000` |
| `TMH_JWT_SECRET` | JWT 密钥 | - |
| `TMH_DATABASE_PATH` | 数据库路径 | `./data/team_memory.db` |
| `TMH_EMBEDDING_PROVIDER` | 嵌入提供商 | `openai_compatible` |
| `TMH_EMBEDDING_BASE_URL` | 嵌入服务地址 | `http://localhost:11434` |
| `TMH_EMBEDDING_MODEL` | 嵌入模型 | `nomic-embed-text` |
| `TMH_EMBEDDING_API_KEY` | 嵌入 API 密钥 | - |
| `TMH_MCP_TOOL_SET` | MCP 工具集 | `read_only` |
| `TMH_LOG_LEVEL` | 日志级别 | `INFO` |

---

## 启动服务 | Starting the Server

```bash
# 方式一：使用入口脚本 | Option 1: Entry script
python main.py                     # 默认 0.0.0.0:8000
python main.py --port 9000         # 自定义端口
python main.py --reload            # 开发模式热重载
python main.py --config my.toml    # 指定配置文件

# 方式二：使用 uvicorn | Option 2: uvicorn directly
uvicorn team_memory_hub.server.app:app --host 0.0.0.0 --port 8000 --reload

# 方式三：模块调用 | Option 3: Module invocation
python -m team_memory_hub --port 8000
```

---

## 使用教程 | Usage Tutorial

### 1. 用户注册与认证 | Registration & Authentication

#### 注册新用户 | Register a new user

```bash
curl -X POST http://localhost:8000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Alice",
    "email": "alice@example.com",
    "password": "secure-password",
    "team_id": "team_default"
  }'
```

#### 获取 JWT Token | Get JWT token

```bash
curl -X POST http://localhost:8000/api/v1/auth/token \
  -H "Content-Type: application/json" \
  -d '{"email": "alice@example.com", "password": "secure-password"}'

# 响应 | Response:
# {
#   "access_token": "eyJ...",
#   "refresh_token": "eyJ...",
#   "token_type": "bearer",
#   "expires_in": 900
# }
```

#### 创建 API Key | Create an API key

```bash
curl -X POST http://localhost:8000/api/v1/keys \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{"name": "my-cli-key", "scope": "full_access"}'

# scope 可选值 | scope options:
# full_access | mcp_only | read_only | sync_only | ingest_only
```

后续请求使用 API Key 更方便：

For subsequent requests, API Key is more convenient:

```bash
export TMH_API_KEY="tmk_xxxxxxxx"
```

---

### 2. CLI 工具使用 | CLI Usage

`tmh` 命令在 `pip install` 后全局可用。

The `tmh` command is globally available after `pip install`.

#### 项目初始化 | Project Initialization

```bash
# 在项目根目录执行 | Run in project root
tmh init

# 指定 AI 工具 | Specify AI tool
tmh init --tool claude-code
tmh init --tool cursor

# 指定服务器 | Specify server
tmh init --server http://tmh.example.com:8000
```

`tmh init` 会：
- 自动检测项目语言、框架、包管理器
- 创建 `.tmh/` 目录和配置
- 根据指定工具生成 Hook/Script

`tmh init` will:
- Auto-detect project languages, frameworks, package managers
- Create `.tmh/` directory and config
- Generate Hook/Script for the specified tool

#### 同步上下文 | Sync Context

```bash
# 同步团队上下文和 AGENTS.md | Sync team context and AGENTS.md
tmh sync

# 静默模式 | Quiet mode
tmh sync --quiet
```

#### 存储记忆 | Store Memory

```bash
# 存储团队决策 | Store a team decision
tmh store --content "JWT 采用滑动窗口刷新策略" \
  --category decision --scope team --tags "auth,jwt"

# 存储经验教训 | Store a lesson learned
tmh store --content "连接池超时设为 30s 可避免数据库锁" \
  --category experience --scope project

# 从 stdin 读取 | Read from stdin
echo "新的编码规范..." | tmh store --content - --category coding_standard
```

#### 搜索记忆 | Search Memory

```bash
# 基础搜索 | Basic search
tmh search "JWT token"

# 按分类过滤 | Filter by category
tmh search "数据库" --category decision

# 限制结果数 | Limit results
tmh search "性能优化" --limit 5
```

#### 查看详情 | View Details

```bash
tmh detail mem_abc12345
```

#### 导入聊天记录 | Ingest Chat Sessions

```bash
# 从文件导入 | Import from file
tmh ingest --file chat.json --tool claude-code

# 指定项目 | Specify project
tmh ingest --file session.json --tool cursor --project proj_xxx

# 支持的工具 | Supported tools:
# claude-code | cursor | opencode | chatbox | codex
```

#### 偏好管理 | Preference Management

```bash
# 查看用户偏好 | List user preferences
tmh prefs list

# 设置偏好 | Set preference
tmh prefs set --key theme --value dark

# 查看生效偏好（含继承） | View effective preferences (with inheritance)
tmh prefs get

# 团队默认偏好 | Team default preferences
tmh prefs team-list
tmh prefs team-set --key max_results --value 50

# 查看自动学习建议 | View auto-learned suggestions
tmh prefs suggestions
```

#### 规范管理 | Spec Management

```bash
# 检测项目画像 | Detect project profile
tmh specs detect

# 规范化规则 | Normalize rules
tmh specs normalize

# 对比规则差异 | Compare rule differences
tmh specs compare
```

#### 记忆整合 | Memory Consolidation

```bash
# 触发扫描 | Trigger scan
tmh consolidation scan

# 查看合并建议 | List merge suggestions
tmh consolidation list

# 接受/拒绝建议 | Accept/reject suggestion
tmh consolidation accept --id sug_xxx
tmh consolidation reject --id sug_xxx
```

---

### 3. HTTP API 使用 | HTTP API Usage

所有 API 端点使用 `/api/v1/` 前缀，认证方式为 JWT 或 API Key。

All API endpoints use the `/api/v1/` prefix, authenticated via JWT or API Key.

#### 记忆 CRUD | Memory CRUD

```bash
# 创建记忆 | Create memory
curl -X POST http://localhost:8000/api/v1/memories \
  -H "Authorization: Bearer $TMH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "使用 pytest-asyncio 的 auto mode 简化异步测试",
    "summary": "pytest-asyncio auto mode 配置",
    "category": "experience",
    "scope": "team",
    "tags": ["testing", "pytest"]
  }'

# 列出记忆 | List memories
curl http://localhost:8000/api/v1/memories \
  -H "Authorization: Bearer $TMH_API_KEY"

# 获取详情（含原文） | Get detail (with content)
curl http://localhost:8000/api/v1/memories/mem_xxx/detail \
  -H "Authorization: Bearer $TMH_API_KEY"

# 更新记忆 | Update memory
curl -X PUT http://localhost:8000/api/v1/memories/mem_xxx \
  -H "Authorization: Bearer $TMH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"content": "更新的内容", "tags": ["updated"]}'

# 删除记忆 | Delete memory
curl -X DELETE http://localhost:8000/api/v1/memories/mem_xxx \
  -H "Authorization: Bearer $TMH_API_KEY"
```

#### 搜索 | Search

```bash
# 混合搜索 | Hybrid search
curl "http://localhost:8000/api/v1/search?q=JWT%20token&limit=10" \
  -H "Authorization: Bearer $TMH_API_KEY"
```

#### Context 引擎 | Context Engine

```bash
# 获取 AI 上下文（自动组装 L0+L1+L2） | Get AI context
curl "http://localhost:8000/api/v1/context/agent?project_id=proj_xxx" \
  -H "Authorization: Bearer $TMH_API_KEY"
```

#### 质量管理 | Quality Management

```bash
# 验证记忆 | Verify memory
curl -X POST http://localhost:8000/api/v1/memories/mem_xxx/verify \
  -H "Authorization: Bearer $TMH_API_KEY"

# 置顶记忆 | Pin memory
curl -X POST http://localhost:8000/api/v1/memories/mem_xxx/pin \
  -H "Authorization: Bearer $TMH_API_KEY"

# 标记过时 | Mark as stale
curl -X POST http://localhost:8000/api/v1/memories/mem_xxx/stale \
  -H "Authorization: Bearer $TMH_API_KEY"
```

#### SSE 实时事件 | SSE Real-time Events

```bash
# 订阅事件流 | Subscribe to event stream
curl -N http://localhost:8000/api/v1/events/stream \
  -H "Authorization: Bearer $TMH_API_KEY"

# 按类型过滤 | Filter by type
curl -N "http://localhost:8000/api/v1/events/stream?types=memory.created,memory.updated" \
  -H "Authorization: Bearer $TMH_API_KEY"
```

---

### 4. MCP Server 集成 | MCP Server Integration

TMH 内置 MCP Server，AI 工具可通过 MCP 协议直接调用。

TMH includes a built-in MCP Server for direct integration with AI tools.

#### 工具列表 | Available Tools

| 工具 Tool | 说明 Description | 最低角色 Min Role |
|---|---|---|
| `search_memory` | 搜索记忆 | viewer |
| `get_memory_detail` | 获取记忆详情 | viewer |
| `store_memory` | 存储新记忆 | member |
| `update_memory` | 更新记忆 | member |
| `delete_memory` | 删除记忆 | member |

#### tool_set 配置 | tool_set Configuration

```bash
# 只读（推荐给 AI 助手） | Read-only (recommended for AI assistants)
TMH_MCP_TOOL_SET=read_only     # search_memory + get_memory_detail

# 读写 | Read-write
TMH_MCP_TOOL_SET=read_write    # + store_memory

# 全 CRUD（管理工具） | Full CRUD (admin tools)
TMH_MCP_TOOL_SET=full_crud     # + update_memory + delete_memory
```

#### 传输协议 | Transport

- **SSE**: `GET /api/v1/mcp/sse` + `POST /api/v1/mcp/messages`
- **Streamable HTTP**: `POST /mcp`

#### Claude Code 集成示例 | Claude Code Integration Example

在 Claude Code 的 MCP 配置中添加：

Add to Claude Code MCP config:

```json
{
  "mcpServers": {
    "tmh": {
      "command": "curl",
      "args": ["-N", "http://localhost:8000/api/v1/mcp/sse"],
      "env": {
        "TMH_API_KEY": "tmk_your_key"
      }
    }
  }
}
```

---

### 5. Web Dashboard | Web 仪表板

访问 `http://localhost:8000/dashboard/` 进入 Web 界面。

Visit `http://localhost:8000/dashboard/` for the web interface.

#### 主要页面 | Main Pages

| 页面 Page | 路径 Path | 说明 Description |
|---|---|---|
| 首页概览 | `/dashboard/` | 统计数据、趋势图、最近活动 |
| 记忆浏览 | `/dashboard/memories` | 记忆列表、过滤、搜索 |
| 搜索调试 | `/dashboard/search` | 搜索引擎测试、权重调整 |
| 规范管理 | `/dashboard/specs` | 团队规范查看 |
| 记忆整合 | `/dashboard/consolidation` | 合并建议审核 |

#### 管理后台 | Admin Panel

| 页面 Page | 路径 Path | 权限 Permission |
|---|---|---|
| 团队管理 | `/dashboard/admin/teams` | admin |
| 项目管理 | `/dashboard/admin/projects` | maintainer+ |
| 用户管理 | `/dashboard/admin/users` | admin |
| API 密钥 | `/dashboard/admin/api-keys` | admin |
| 审核管理 | `/dashboard/admin/curation` | maintainer+ |
| 系统配置 | `/dashboard/admin/system` | admin |

---

### 6. AI 工具集成 | AI Tool Integration

TMH 支持多种 AI 编码工具的自动集成。

TMH supports automatic integration with multiple AI coding tools.

#### 支持的工具 | Supported Tools

| 工具 Tool | 上传方式 Upload Tier | 说明 Description |
|---|---|---|
| Claude Code | Tier 1 - Hook | 零 token，post_session Hook 自动回调 |
| OpenCode | Tier 1 - Hook | 零 token，Hook 自动回调 |
| Cursor | Tier 2 - Script | ~100 tokens/次，.tmh/upload.py |
| Codex | Tier 2 - Script | ~100 tokens/次，脚本上传 |
| Chatbox | Tier 3 - MCP | ~200 tokens/次，MCP 工具调用 |

#### 项目接入流程 | Project Onboarding

```bash
# 1. 初始化（选择你使用的 AI 工具） | Initialize (choose your AI tool)
tmh init --tool claude-code

# 2. 同步团队上下文 | Sync team context
tmh sync

# 3. 开始使用 | Start using
# AI 工具会自动获取团队记忆作为上下文
# AI tools will automatically get team memories as context
```

---

## API 端点总览 | API Endpoints Overview

| 端点 Endpoint | 方法 Method | 说明 Description |
|---|---|---|
| `/api/v1/auth/register` | POST | 用户注册 |
| `/api/v1/auth/token` | POST | 获取 JWT |
| `/api/v1/auth/refresh` | POST | 刷新 JWT |
| `/api/v1/keys` | GET/POST | API Key 管理 |
| `/api/v1/memories` | GET/POST | 记忆列表/创建 |
| `/api/v1/memories/{id}` | GET/PUT/DELETE | 记忆 CRUD |
| `/api/v1/memories/{id}/detail` | GET | 记忆原文 |
| `/api/v1/memories/{id}/verify` | POST | 验证记忆 |
| `/api/v1/memories/{id}/pin` | POST | 置顶记忆 |
| `/api/v1/memories/{id}/stale` | POST | 标记过时 |
| `/api/v1/search` | GET | 混合搜索 |
| `/api/v1/context/agent` | GET | AI Context 组装 |
| `/api/v1/teams` | GET/POST | 团队管理 |
| `/api/v1/projects` | GET/POST | 项目管理 |
| `/api/v1/consolidation/scan` | POST | 触发合并扫描 |
| `/api/v1/consolidation/suggestions` | GET | 合并建议列表 |
| `/api/v1/consolidation/suggestions/{id}/accept` | POST | 接受合并 |
| `/api/v1/curation/run` | POST | 运行维护任务 |
| `/api/v1/preferences/user` | GET/POST | 用户偏好 |
| `/api/v1/preferences/effective` | GET | 生效偏好 |
| `/api/v1/events/stream` | GET | SSE 事件流 |
| `/api/v1/specs` | GET/POST | 规范管理 |
| `/api/v1/chats/ingest` | POST | 聊天记录导入 |
| `/api/v1/mcp/sse` | GET | MCP SSE 传输 |
| `/mcp` | POST | MCP Streamable HTTP |
| `/api/v1/health` | GET | 健康检查 |
| `/api/v1/admin/*` | - | 管理后台 API |

完整 API 文档：启动服务后访问 `http://localhost:8000/docs`

Full API docs: visit `http://localhost:8000/docs` after starting the server

---

## 项目结构 | Project Structure

```
src/team_memory_hub/
  cli.py                   # CLI 入口（tmh 全局命令）
  config.py                # TOML + 环境变量配置
  __main__.py              # python -m team_memory_hub 服务器入口
  core/
    memory_store.py        # 记忆 CRUD + 文件一致性
    memory_file_store.py   # Markdown 文件存储
    search_engine.py       # 混合搜索引擎
    context_engine.py      # 三层 Context 组装
    context_cache.py       # Context 缓存
    context_syncer.py      # 上下文同步
    preference_engine.py   # 用户偏好引擎
    memory_consolidator.py # 合并建议生成
    memory_extractor.py    # 聊天记忆提取
    curation.py            # 自动维护任务
    rbac.py                # 权限矩阵
    audit.py               # 审计日志
    write_queue.py         # 异步写队列
    agents_generator.py    # AGENTS.md 生成
    project_detector.py    # 项目画像检测
    rule_normalizer.py     # 规则规范化
    spec_matcher.py        # 规范匹配
    spec_deduplicator.py   # 规范去重
    spec_manager.py        # 规范管理
  server/
    app.py                 # FastAPI 应用工厂
    dependencies.py        # 认证 & DI 依赖
    event_bus.py           # SSE 事件总线
    mcp_server.py          # MCP JSON-RPC Server
    routes/                # API 路由模块
  providers/
    embedding/             # 嵌入提供商 (Gemini, OpenAI, ONNX, Compatible)
    llm/                   # LLM 提供商 (Claude, Gemini, Rules)
  chat_adapters/           # 聊天适配器 (Claude Code, Cursor, OpenCode, Chatbox, Codex)
  client_adapters/         # 客户端适配器
  dashboard/
    templates/             # Jinja2 + HTMX 模板
    static/                # CSS, JS
  storage/
    database.py            # aiosqlite 封装 + 迁移管理
    models.py              # Pydantic 数据模型
    migrations/            # Schema 迁移 (v1, v1_5, v1_6)
```

---

## 测试 | Testing

```bash
# 运行所有测试 | Run all tests
pytest

# 带覆盖率 | With coverage
pytest --cov=team_memory_hub

# 单个测试文件 | Single test file
pytest tests/test_memories.py
pytest tests/test_cli.py
pytest tests/test_mcp.py

# 快速失败 | Fail fast
pytest -x --tb=short
```

---

## 许可证 | License

MIT