# https://github.com/d4n-larsson/aegisdb 项目说明书

生成时间：2026-06-28 19:11:53 UTC

## 目录

- [Project Overview & System Architecture](#page-1)
- [Core Server, Storage Engine & Recovery](#page-2)
- [Wire Protocol, Query Engine & Configuration](#page-3)
- [Authentication, Deployment & Claude Code Integration](#page-4)

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

## Project Overview & System Architecture

### 相关页面

相关主题：[Core Server, Storage Engine & Recovery](#page-2), [Wire Protocol, Query Engine & Configuration](#page-3), [Authentication, Deployment & Claude Code Integration](#page-4)

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

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

- [CLAUDE.md](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md)
- [site/index.html](https://github.com/d4n-larsson/aegisdb/blob/main/site/index.html)
- [integrations/claude-code/README.md](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/README.md)
- [integrations/claude-code/aegis_mcp/server.py](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/server.py)
- [integrations/claude-code/aegis_mcp/capture.py](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/capture.py)
- [src/util/client.c](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/client.c)
- [third_party/cjson/cJSON.h](https://github.com/d4n-larsson/aegisdb/blob/main/third_party/cjson/cJSON.h)
</details>

# 项目概述与系统架构

## 项目定位与设计目标

AegisDB 是一个面向 AI Agent 的持久化内存数据库，核心目标是为会话式 Agent 提供"超出上下文窗口"的长期记忆能力 资料来源：[site/index.html](https://github.com/d4n-larsson/aegisdb/blob/main/site/index.html)。它以 C 语言实现，通过 TCP 提供 NDJSON（换行分隔 JSON）的线协议，单行 JSON 即一次请求或响应 资料来源：[CLAUDE.md:1-3](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md)。

项目主页强调三个核心特征：写入即追加（append-only log）的不可篡改事件记录、按"含义 / 时间 / 标签"三维检索、以及为不同记忆生命周期设计的差异化存储模型 资料来源：[site/index.html](https://github.com/d4n-larsson/aegisdb/blob/main/site/index.html)。所有设计都围绕"Agent 不应反复遗忘"这一场景展开。

## 核心架构与组件

系统由两大部分组成：C 语言编写的数据库服务，以及 Claude Code 集成层。两者通过 NDJSON/TCP 通信：

```mermaid
flowchart LR
    CC[Claude Code] -->|MCP stdio| MCP[aegis_mcp.server]
    CC -->|Hooks| HK[recall / capture]
    MCP -->|NDJSON/TCP| DB[AegisDB C Server]
    HK -->|NDJSON/TCP| DB
    DB --> Log[(append.log)]
    DB --> Idx[Vector / Tag / Time Index]
```

源码布局遵循"运行时管道"原则：`src/` 与 network → protocol → query → storage 流水线一一对应；`include/aegisdb/` 存放公共头文件；`docs/` 提供线协议参考与快速入门；`integrations/claude-code/` 是 Claude Code 集成层 资料来源：[CLAUDE.md:18-22](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md)。

线协议层面，客户端工具 `src/util/client.c` 中可见请求结构示例（如 `{"operation":"put", ...}`、`{"operation":"search","query":"...","top_k":N}`），与官方文档示例一致 资料来源：[src/util/client.c](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/client.c)。JSON 解析复用嵌入式第三方库 cJSON（v1.7.19），随源码发布在 `third_party/cjson/` 资料来源：[third_party/cjson/cJSON.h:45-47](https://github.com/d4n-larsson/aegisdb/blob/main/third_party/cjson/cJSON.h)。

## 内存模型与数据流

AegisDB 将记忆划分为三种类型，各自拥有独立的生命周期与索引策略 资料来源：[site/index.html](https://github.com/d4n-larsson/aegisdb/blob/main/site/index.html)：

| 类型 | 生命周期 | 特征 |
|------|---------|------|
| episodic（情景） | 不可变 | append-only 事件，是索引重建的"真相之源" |
| semantic（语义） | 可更新 | 最新版本胜出，旧记录自动让位 |
| working（工作） | 短期 | 按会话环形缓冲，带 TTL 过期 |

检索支持三种路径——向量相似度、标签 `all/any` 匹配、时间区间——每条路径都走专用索引而非全表扫描；上下文图通过有向边链接记忆，并支持广度优先遍历以"拉取相关内容" 资料来源：[site/index.html](https://github.com/d4n-larsson/aegisdb/blob/main/site/index.html)。`--embedding-dim`（如 1024）在启动时固定，向量维度一经设定便不可更改，因此必须在服务端、MCP 集成与嵌入提供者之间保持一致 资料来源：[integrations/claude-code/README.md](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/README.md)。

## 构建、运行与集成

构建支持两套系统：`make`（含 `make test`、`make integration`、`make check`）与 CMake（`cmake -B build && cmake --build build`）。需注意 `Makefile` 并不追踪头文件依赖——编辑 `include/` 下任何头文件后必须先 `make clean && make`，否则可能出现隐式的结构体/ABI 不匹配 资料来源：[CLAUDE.md:5-11](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md)。

启动命令非常直接：

```sh
./build/aegisdb --data-dir ./data --port 9470 --embedding-dim 1024
```

通过 `--auth-token <tok>` 或 `--auth-token-file <path>` 即可启用认证 资料来源：[CLAUDE.md:13-16](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md)。容器化发布版本（v0.3.0）将数据卷映射至 `/data`，并暴露 9470 端口 资料来源：[社区发布说明](https://github.com/d4n-larsson/aegisdb/compare/v0.2.0...v0.3.0)。

Claude Code 集成层（`integrations/claude-code/`）采用"薄包装 + 核心模块"模式：仅 `server.py` 依赖可选的 `mcp` SDK，所有业务逻辑位于 `aegis_mcp/` 下的零依赖模块中 资料来源：[integrations/claude-code/aegis_mcp/server.py:1-7](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/server.py)。该层提供五项 MCP 工具（`memory_save` / `memory_search` / `memory_get` / `memory_update` / `memory_relate`）、`UserPromptSubmit` 钩子实现"自动召回"、`SessionEnd` 钩子实现"自动捕获"；其中 `capture.py` 通过显著性评分（`_SALIENCE_MARKERS`）、临时性标记（`_EPHEMERAL_MARKERS`）与标签推断（`_TAG_RULES`）决定哪些会话内容值得持久化 资料来源：[integrations/claude-code/aegis_mcp/capture.py:1-25](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/capture.py)。集成始终为 best-effort——若后端不可达，Agent 依然可用，不会因为记忆系统故障而中断会话 资料来源：[integrations/claude-code/README.md](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/README.md)。

## 另请参阅

- 内存模型与生命周期详解
- NDJSON 线协议参考
- Claude Code 集成安装与配置

---

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

## Core Server, Storage Engine & Recovery

### 相关页面

相关主题：[Project Overview & System Architecture](#page-1), [Wire Protocol, Query Engine & Configuration](#page-3), [Authentication, Deployment & Claude Code Integration](#page-4)

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

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

- [README.md](https://github.com/d4n-larsson/aegisdb/blob/main/README.md)
- [CLAUDE.md](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md)
- [include/aegisdb/log.h](https://github.com/d4n-larsson/aegisdb/blob/main/include/aegisdb/log.h)
- [src/util/config.c](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/config.c)
- [src/query/query_engine.c](https://github.com/d4n-larsson/aegisdb/blob/main/src/query/query_engine.c)
- [src/util/client.c](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/client.c)
</details>

# Core Server、Storage Engine 与 Recovery

## 概览

AegisDB 是一个使用 C 语言编写的独立数据库服务器，专门为 AI Agent 的记忆场景进行优化。整个运行时由三大子系统紧密协作：

- **网络与协议层**：TCP 之上的 NDJSON 协议（默认端口 9470）
- **存储引擎**：日志结构（log-structured）持久化层 + 多套专用索引
- **恢复子系统**：启动期 checkpoint + 日志尾部重放 + 损坏帧容错

代码布局是运行时管线的镜像——`src/` 下依次为 `server/`、`protocol/`、`query/`、`storage/`、`memory/`、`util/`；公共头文件位于 `include/aegisdb/`（资料来源：[README.md:54-63]()、[CLAUDE.md:18-19]()）。

```mermaid
flowchart LR
  Client[TCP Client] -->|NDJSON 行| Server[server/tcp_server.c<br/>Worker 线程池]
  Server --> Parser[protocol/json_request.c<br/>请求解析]
  Parser --> Router[query/query_engine.c<br/>操作路由]
  Router --> Log[storage/log.c<br/>追加日志 v2 帧]
  Log --> Checkpoint[memory.index]
  Log -->|启动时| Recovery[尾部 replay + 跳过坏帧]
```

## 网络与核心服务器

服务器监听 TCP 端口并以换行符分隔的 JSON 作为请求格式。CLI 客户端支持 `ping`、`stats`、`insert`、`put`、`get`、`delete`、`search`、`relate`、`traverse` 等命令（资料来源：[src/util/client.c:1-12]()）。

构建与运行示例：

```sh
make                           # 或 cmake -B build && cmake --build build
./build/aegisdb --data-dir ./data --port 9470 --embedding-dim 1024
```

需要认证时附加 `--auth-token <tok>` 或 `--auth-token-file <path>`。令牌按 `命名空间 + 作用域（ro/rw/admin）` 绑定，实现多租户隔离；当未提供 `--namespace` 时为全局管理令牌，未提供 `--token` 时由 `/dev/urandom` 随机生成（资料来源：[src/util/client.c:73-100]()、[src/util/config.c:1-22]()）。

## 存储引擎

存储引擎采用日志结构设计，并维护四套专用索引：

| 索引 | 用途 |
|------|------|
| 哈希索引 | 按 ID O(1) 查找 |
| 时间索引 | 时间区间扫描 |
| 反向标签索引 | tag 查询（`all` / `any`） |
| 向量索引 | 精确余弦相似度搜索 |

### v2 帧格式

每个写入磁盘的帧采用自描述布局（资料来源：[include/aegisdb/log.h:5-29]()）：

```
[MAGIC: u32 LE][LEN: u32 LE][PAYLOAD_CRC: u32 LE][HEADER_CRC: u32 LE][PAYLOAD: LEN bytes]
```

- **MAGIC**：固定同步标记，使恢复时可在损坏后重新对齐到下一帧
- **HEADER_CRC**：覆盖前 12 字节，将头部故障与负载故障区分开
- **PAYLOAD_CRC**：覆盖负载区
- **legacy v1 日志**（8 字节 `[CRC][LEN]`，无 magic）在打开时被自动检测并就地迁移为 v2

写入端使用 `pthread_mutex_t wlock` 串行化追加，并通过 `fsync_batch` 决定耐久性策略（`sync` / `batch` / `interval`）。

### 查询路由与阶段门控

`query/query_engine.c` 在路由层实现了 **phase gating** 机制（资料来源：[src/query/query_engine.c:16-20]()）：

```c
static aegis_status_t require_phase(const AegisDB *db, int needed) {
    return (db->config.enabled_phase >= needed) ? AEGIS_OK
                                                : AEGIS_ERR_NOT_READY;
}
```

未达到所需阶段的操作会以 `AEGIS_ERR_NOT_READY` 拒绝，允许运维分阶段开启新功能。通用校验对 `data_len` 与 `max_payload_bytes` 比对，并对 tag 名称施加严格规则（仅字母数字、下划线、短横线；长度 1–64）。

## Recovery 机制

AegisDB 在启动时按以下顺序恢复（资料来源：[README.md:84-91]()）：

1. **加载索引 checkpoint** `memory.index`
2. **重放日志尾部**：仅重放 checkpoint 之后的部分
3. **回退到全量扫描**：当 checkpoint 缺失或损坏时
4. **裁剪撕裂尾部**：因中途崩溃导致的不完整帧
5. **跳过内部损坏帧**：使周围记录仍可加载

由于 HEADER_CRC 独立于 PAYLOAD_CRC 进行校验，**单个损坏帧不再强制丢弃整条尾部**——扫描器跳过坏帧后即可继续恢复其后的完好帧。这是 v2 帧格式相对 v1 的核心改进。

手动验证脚本：

```sh
# 1. 插入若干记录
# 2. kill -9 <pid>
# 3. 重启 → 日志输出 "recovery complete: N records loaded"
# 4. get 每个 ID → 全部返回完整
```

## 常见陷阱与注意事项

- **Makefile 不追踪头依赖**：编辑 `include/` 下任何头文件后必须 `make clean && make`，否则陈旧对象文件可能导致**静默的 struct/ABI 不匹配**（资料来源：[CLAUDE.md:9-11]()）。
- **令牌明文传输**：应在加密信道（VPN、SSH 隧道或 TLS 代理）后运行（资料来源：[src/util/config.c:14-19]()）。
- **namespace 与 scope 关系**：`ro`/`rw` 必须显式指定 namespace；缺省 `--token` 时由 `/dev/urandom` 生成（资料来源：[src/util/client.c:73-100]()）。

## See Also

- [Claude Code 集成](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/README.md)
- [v0.3.0 发布说明](https://github.com/d4n-larsson/aegisdb/compare/v0.2.0...v0.3.0)

---

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

## Wire Protocol, Query Engine & Configuration

### 相关页面

相关主题：[Project Overview & System Architecture](#page-1), [Core Server, Storage Engine & Recovery](#page-2), [Authentication, Deployment & Claude Code Integration](#page-4)

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

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

- [src/protocol/json_request.c](https://github.com/d4n-larsson/aegisdb/blob/main/src/protocol/json_request.c)
- [src/protocol/json_response.c](https://github.com/d4n-larsson/aegisdb/blob/main/src/protocol/json_response.c)
- [src/query/query_engine.c](https://github.com/d4n-larsson/aegisdb/blob/main/src/query/query_engine.c)
- [src/util/client.c](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/client.c)
- [src/util/config.c](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/config.c)
- [include/aegisdb/json_request.h](https://github.com/d4n-larsson/aegisdb/blob/main/include/aegisdb/json_request.h)
- [include/aegisdb/json_response.h](https://github.com/d4n-larsson/aegisdb/blob/main/include/aegisdb/json_response.h)
- [include/aegisdb/query_engine.h](https://github.com/d4n-larsson/aegisdb/blob/main/include/aegisdb/query_engine.h)
- [integrations/claude-code/aegis_mcp/results.py](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/results.py)
</details>

# Wire Protocol, Query Engine & Configuration

## 概述

AegisDB 是一款面向 AI 代理的持久化内存数据库，采用 **C 语言** 实现的 TCP 服务器，承载着三类内存（episodic、semantic、working）的存取操作。整条数据流可以概括为：客户端通过 **NDJSON（Newline-Delimited JSON）** 协议发送一行 JSON 请求，服务器解析后交由查询引擎分发，最终落地到追加日志 `memory.log` 与内存索引中。`README.md` 指出 `protocol/` 负责 JSON 解析与响应构造，`query/` 负责操作路由 ([README.md: 项目结构布局](https://github.com/d4n-larsson/aegisdb/blob/main/README.md))。

配置层（`src/util/config.c`）通过命令行参数与环境变量控制端口、数据目录、向量维度、鉴权令牌等关键参数；启动日志中会打印 `recovery complete: N records loaded` 形式的恢复摘要 ([CLAUDE.md: 运行说明](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md))。

---

## 线路协议（Wire Protocol）

### 请求与响应格式

AegisDB 的线路协议是 **一行 JSON 进、一行 JSON 出**：每条消息由换行符 `\n` 终止，连接复用同一 TCP 长连接，无 SDK、无驱动层要求 ([site/index.html: 协议说明段落](https://github.com/d4n-larsson/aegisdb/blob/main/site/index.html))。`json_request.h` 负责将原始字节流解析为内部请求结构，`json_response.h` 则构建 `{ "ok": true, ... }` 或 `{ "ok": false, "error": { "code": ..., "message": ... } }` 形式的响应对象 ([include/aegisdb/json_response.h: 8-20](https://github.com/d4n-larsson/aegisdb/blob/main/include/aegisdb/json_response.h))。

```json
{"operation":"insert","type":"episodic","tags":["user"],"data":"Prefers dark mode"}
→ {"ok":true,"record":{"id":1,"type":"episodic", ...}}
```

### 错误码体系

服务器通过 `json_error_status()` 将内部 `aegis_status_t` 映射为稳定的线路错误码。集成层在 `aegis_mcp/results.py` 中维护了一张映射表 `AEGIS_ERROR_MAP`，把 `NOT_FOUND`、`INVALID_REQUEST`、`PAYLOAD_TOO_LARGE`、`IMMUTABLE`、`NOT_READY`、`UNAUTHORIZED`、`FORBIDDEN`、`INTERNAL` 转译为上层可读词汇（如 `not_found`、`unavailable`）([integrations/claude-code/aegis_mcp/results.py: AEGIS_ERROR_MAP](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/results.py))。这种双层翻译确保底层协议演进时上层契约保持稳定。

```mermaid
flowchart LR
    A[Client] -- NDJSON / TCP --> B[Server IO]
    B --> C[json_request.c 解析]
    C --> D[query_engine.c 路由]
    D --> E[存储与索引]
    E --> D
    D --> F[json_response.c 构造]
    F -- 一行 JSON --> A
```

---

## 查询引擎（Query Engine）

### 操作路由

`query_engine.c` 的头部注释列出该模块承担的职责：T016 路由器、T020–T022 基础 CRUD、T029–T031 语义更新与时间/标签检索、T037–T038 语义检索与重排、T043–T044 工作内存与晋升、T047–T049 图边与代理作用域、T055 阶段门控 ([src/query/query_engine.c: 1-9](https://github.com/d4n-larsson/aegisdb/blob/main/src/query/query_engine.c))。`query_engine_dispatch()` 读取 `operation` 字段后分派到 `qe_insert`、`qe_get`、`qe_search`、`qe_relate` 等子例程。

### 阶段门控（Phase Gating）

`require_phase()` 函数检查 `db->config.enabled_phase` 与操作所需最低阶段的比较：未达到启动阶段时返回 `AEGIS_ERR_NOT_READY`。这意味着即使客户端已建立连接，索引尚未构建完成前部分操作也会被拒绝 ([src/query/query_engine.c: 13-17](https://github.com/d4n-larsson/aegisdb/blob/main/src/query/query_engine.c))。

### 输入校验

- **标签校验**：`valid_tag()` 要求长度在 1–64 之间，且仅允许字母数字、`_`、`-` ([src/query/query_engine.c: 21-28](https://github.com/d4n-larsson/aegisdb/blob/main/src/query/query_engine.c))。
- **载荷上限**：`validate_common()` 将 `data_len` 与 `db->config.max_payload_bytes` 比较，超出即报错，避免恶意大请求拖垮服务器 ([src/query/query_engine.c: 30-32](https://github.com/d4n-larsson/aegisdb/blob/main/src/query/query_engine.c))。

### 语义索引接口

`semantic_index.h` 定义了 `SemanticIndex` 抽象：当前实现为**精确余弦扫描**，注释明确指出 `R-008` 调研建议的目标结构是 HNSW，但与单 C17 二进制目标冲突，因此保留为可替换的精确实现 ([include/aegisdb/semantic_index.h: 1-12](https://github.com/d4n-larsson/aegisdb/blob/main/include/aegisdb/semantic_index.h))。`semantic_index_search()` 按余弦相似度返回 top-K 的 `id` 与 `score`，查询引擎在此基础上做相似度 × 重要度的二次重排。

---

## 配置与命令行客户端

### 常用启动参数

`CLAUDE.md` 给出了典型启动命令：`./build/aegisdb --data-dir ./data --port 9470 --embedding-dim 1024`，并通过 `--auth-token` 或 `--auth-token-file` 启用鉴权 ([CLAUDE.md: 运行说明](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md))。客户端（`src/util/client.c`）中内置的 `usage()` 文本进一步说明：主机、端口、令牌默认读取 `$AEGIS_HOST` / `$AEGIS_PORT` / `$AEGIS_TOKEN`（默认 `127.0.0.1:9470`、无令牌），且客户端在收到 `ok` 响应时退出码为 `0` ([src/util/client.c: usage 文本](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/client.c))。

### CLI 客户端的操作映射

| 子命令 | 请求字段 | 说明 |
| --- | --- | --- |
| `ping` / `stats` | `{"operation": <op>}` | 健康检查与统计 |
| `get` / `delete` | `{"operation": <op>, "id": N}` | 按主键访问 |
| `put` | `type`/`data`/`tags`/`importance`/`confidence`/`session`/`ttl-ms` | 通用写入入口 |

完整子命令的请求组装集中在 `build_request()` 中，它根据 `cmd` 字符串分流到对应分支 ([src/util/client.c: build_request](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/client.c))。这种**前端命令与后端 operation 字段一一对应**的设计让协议保持平坦，避免私有扩展污染接口。

### 容器化与默认值

v0.3.0 发布镜像 `ghcr.io/d4n-larsson/aegisdb:0.3.0` 暴露 `9470` 端口并把 `/data` 挂载为命名卷 `aegis-data` ([社区发布说明: v0.3.0](https://github.com/d4n-larsson/aegisdb/releases))。在该模式下，配置文件显式传入的参数将覆盖容器环境变量；`/data` 目录承担 `memory.log` 与 `memory.index` 的持久化职责。

---

## See Also

- [Claude Code 集成总览](./Claude-Code-Integration.md)
- [持久化与崩溃恢复](./Persistence-and-Recovery.md)
- [三类内存模型](./Memory-Model.md)

---

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

## Authentication, Deployment & Claude Code Integration

### 相关页面

相关主题：[Project Overview & System Architecture](#page-1), [Core Server, Storage Engine & Recovery](#page-2), [Wire Protocol, Query Engine & Configuration](#page-3)

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

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

- [CLAUDE.md](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md)
- [src/util/config.c](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/config.c)
- [src/util/client.c](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/client.c)
- [integrations/claude-code/README.md](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/README.md)
- [integrations/claude-code/aegis_mcp/server.py](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/server.py)
- [integrations/claude-code/aegis_mcp/results.py](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/results.py)
- [integrations/claude-code/aegis_mcp/capture.py](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/capture.py)
- [site/index.html](https://github.com/d4n-larsson/aegisdb/blob/main/site/index.html)
</details>

# 身份验证、部署与 Claude Code 集成

AegisDB 是面向 AI 代理的持久化内存数据库：核心是 C 写的 NDJSON/TCP 服务，并提供面向 Claude Code 的 MCP 集成。本页将这三个紧密耦合的主题集中说明：访问控制、生产部署，以及让 Claude Code 拥有"跨会话长期记忆"的集成方案。

## 1. 身份验证机制

AegisDB 在 `src/util/config.c` 与 `src/util/client.c` 中实现了基于共享令牌的访问控制。默认情况下服务器**不要求身份验证**；启用后所有请求必须携带明文 token，官方建议在 VPN、SSH 隧道或 TLS 反代之后运行 资料来源：[src/util/config.c:8-30](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/config.c#L8-L30)。

- **服务端注入**：`--auth-token <tok>` 直接传入，`--auth-token-file <path>` 从文件读取，文件中的 token 在静态存储时使用 `sha256$<hex>` 哈希 资料来源：[src/util/config.c:8-30](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/config.c#L8-L30)。
- **客户端默认值**：`$AEGIS_HOST` / `$AEGIS_PORT` / `$AEGIS_TOKEN`（默认 `127.0.0.1` / `9470` / 无） 资料来源：[src/util/client.c:1-80](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/client.c#L1-L80)。
- **命名空间与作用域**：`--namespace` 绑定作用域，`--scope` 取 `ro`（只读）、`rw`（读写）或 `admin`（全局管理）；`ro` / `rw` 必须配合 namespace，`admin` 在无 namespace 时为全局 token 资料来源：[src/util/client.c:1-60](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/client.c#L1-L60)。
- **生成与哈希**：`gen-token` 子命令可在 `/dev/urandom` 上生成随机 hex token；`--hash-token <token>` 单独打印 `sha256$<hex>`，便于直接粘贴进 token 文件 资料来源：[src/util/config.c:8-30](https://github.com/d4n-larsson/aegisdb/blob/main/src/util/config.c#L8-L30)。
- **错误码映射**：服务端 `UNAUTHORIZED` / `FORBIDDEN` 在 MCP 集成层被稳定映射为 `unauthorized` / `forbidden`，便于上层模型识别 资料来源：[integrations/claude-code/aegis_mcp/results.py:1-30](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/results.py#L1-L30)。

## 2. 部署方式

AegisDB 同时支持原生构建与容器化部署。

- **原生构建**：`make`，或 CMake 路径 `cmake -B build && cmake --build build`；测试分别用 `make test`（C 单元）、`make integration`（线协议契约）、`make check`（合并） 资料来源：[CLAUDE.md:5-20](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md#L5-L20)。
- **典型启动**：`./build/aegisdb --data-dir ./data --port 9470 --embedding-dim 1024` 资料来源：[CLAUDE.md:15-20](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md#L15-L20)。
- **构建陷阱**：`Makefile` 不跟踪头文件依赖；修改 `include/` 下任何头文件后必须 `make clean && make`，否则陈旧 `.o` 文件会产生隐式的结构体/ABI 不匹配 资料来源：[CLAUDE.md:5-15](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md#L5-L15)。
- **容器化部署（v0.3.0）**：

  ```sh
  docker run -p 9470:9470 -v aegis-data:/data \
    ghcr.io/d4n-larsson/aegisdb:0.3.0
  ```

  将数据卷挂载到 `/data`，`9470` 暴露为 NDJSON/TCP 服务；如需鉴权，请改用 compose 或包装脚本传入 `--auth-token-file`。

## 3. Claude Code 集成

`integrations/claude-code/` 下的 Python 包让 Claude Code 拥有跨会话的长期记忆，整体遵循"尽力而为"原则：AegisDB 不可达时 agent 仍可正常工作 资料来源：[integrations/claude-code/README.md:1-30](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/README.md#L1-L30)。

### 3.1 数据流

```mermaid
flowchart LR
  A[Claude Code] -- MCP stdio --> B[aegis_mcp.server]
  A -- hooks --> C[recall / capture]
  B -- NDJSON/TCP --> D[AegisDB]
  C -- NDJSON/TCP --> D
  C -- embed API --> E[Voyage / Local / None]
  C -- vectors --> D
```

### 3.2 组件职责

- **MCP 工具**（`memory_save` / `_search` / `_get` / `_update` / `_relate`）：由模型显式调用的长期记忆 API 资料来源：[integrations/claude-code/README.md:10-30](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/README.md#L10-L30)。
- **`UserPromptSubmit` hook**：每轮对话前自动检索相关记忆，并在时间预算内注入上下文。
- **`SessionEnd` hook**：会话结束时由 `score_text` 依据标记词计算 `salience`，并通过 `_TAG_RULES` 推断标签；带 *don't remember* / *ephemeral* / *secret* 等 `_EPHEMERAL_MARKERS` 的内容会被排除 资料来源：[integrations/claude-code/aegis_mcp/capture.py:1-50](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/capture.py#L1-L50)。
- **嵌入向量**：可插拔的 provider（Voyage / 本地 / none）将文本转为向量；集成层从不向 agent 索要向量 资料来源：[integrations/claude-code/README.md:10-25](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/README.md#L10-L25)。

### 3.3 启动校验

`build_tools` 启动时若 provider 可用，会比较 `provider.dimension()` 与 `config.embedding_dimensions`，不一致立即退出，避免后续搜索的隐性失败 资料来源：[integrations/claude-code/aegis_mcp/server.py:15-40](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/server.py#L15-L40)。同时 `check_startup` 探测后端可达性，告警统一打印到 stderr。

### 3.4 分发与隔离

每个项目通过 namespace 隔离自己的记忆；MCP server 以 PyPI 包名 `aegisdb-mcp` 发布，可由 `uvx` 按需拉取并执行，无需本地 clone 资料来源：[integrations/claude-code/README.md:1-30](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/README.md#L1-L30)。

## 4. 常见失败模式

- **容器启动但 token 不生效**：检查 `AEGISDB_LOG_LEVEL=debug` 输出，并确认 `--auth-token-file` 中的格式为 `sha256$<hex>`。
- **维度不匹配**：`aegisdb --embedding-dim` 与 MCP 端 `embedding_dimensions` 必须一致，否则搜索静默退化 资料来源：[integrations/claude-code/aegis_mcp/server.py:15-40](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/aegis_mcp/server.py#L15-L40)。
- **`/mcp` 中 server 已连接但工具报错**：通常是 AegisDB 不可达；agent 仍可继续使用，不会中断 资料来源：[integrations/claude-code/README.md:1-30](https://github.com/d4n-larsson/aegisdb/blob/main/integrations/claude-code/README.md#L1-L30)。
- **改头文件后编译异常**：必须 `make clean && make` 资料来源：[CLAUDE.md:5-15](https://github.com/d4n-larsson/aegisdb/blob/main/CLAUDE.md#L5-L15)。

## 参见

- 仓库主页：[d4n-larsson/aegisdb](https://github.com/d4n-larsson/aegisdb)
- 线协议与快速上手：`docs/`
- v0.3.0 更新日志：[compare v0.2.0...v0.3.0](https://github.com/d4n-larsson/aegisdb/compare/v0.2.0...v0.3.0)

---

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

---

## Doramagic 踩坑日志

项目：d4n-larsson/aegisdb

摘要：发现 9 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 依赖 Docker 环境。

## 1. 安装坑 · 依赖 Docker 环境

- 严重度：medium
- 证据强度：runtime_trace
- 发现：安装/运行入口包含 Docker 命令：docker run -p 9470:9470 -v aegis-data:/data ghcr.io/d4n-larsson/aegisdb:latest # or pin a release: ghcr.io/d4n-larsson/aegisdb:0.1.0
- 对用户的影响：非工程用户可能没有 Docker，启动成本明显增加。
- 复现命令：`docker run -p 9470:9470 -v aegis-data:/data ghcr.io/d4n-larsson/aegisdb:latest # or pin a release: ghcr.io/d4n-larsson/aegisdb:0.1.0`
- 证据：identity.distribution | https://github.com/d4n-larsson/aegisdb | docker run -p 9470:9470 -v aegis-data:/data ghcr.io/d4n-larsson/aegisdb:latest # or pin a release: ghcr.io/d4n-larsson/aegisdb:0.1.0

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

- 严重度：medium
- 证据强度：source_linked
- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- 证据：capability.host_targets | https://github.com/d4n-larsson/aegisdb | host_targets=claude_code, claude

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

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 证据：capability.assumptions | https://github.com/d4n-larsson/aegisdb | README/documentation is current enough for a first validation pass.

## 4. 运行坑 · 运行可能依赖外部服务

- 严重度：medium
- 证据强度：source_linked
- 发现：项目说明出现 external service/cloud/webhook/database 等运行依赖关键词。
- 对用户的影响：本地安装成功不等于能力可用，外部服务不可用会阻断体验。
- 证据：packet_text.keyword_scan | https://github.com/d4n-larsson/aegisdb | matched external service / cloud / webhook / database keyword

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

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 证据：evidence.maintainer_signals | https://github.com/d4n-larsson/aegisdb | last_activity_observed missing

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 证据：downstream_validation.risk_items | https://github.com/d4n-larsson/aegisdb | no_demo; severity=medium

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

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 证据：risks.scoring_risks | https://github.com/d4n-larsson/aegisdb | no_demo; severity=medium

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

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 证据：evidence.maintainer_signals | https://github.com/d4n-larsson/aegisdb | issue_or_pr_quality=unknown

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

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 证据：evidence.maintainer_signals | https://github.com/d4n-larsson/aegisdb | release_recency=unknown

<!-- canonical_name: d4n-larsson/aegisdb; human_manual_source: deepwiki_human_wiki -->
