HiveBrain
Local-first knowledge base for developer teams.
Every bug you fix teaches the next session what to do.
______________________________________________________________________
HiveBrain 是一个自托管的知识库,用于捕获模式、gotchas、调试解决方案和代码片段,然后通过web UI、REST API和本地Claude code工具立即进行搜索。它在你的机器上运行,将所有内容存储在SQLite中,并作为MCP服务器连接到Claude Code中,这样每个AI会话都可以搜索并贡献共享知识。零云、零账户、零延迟。
入门指南 · API 参考 · MCP工具 · 搜索 · 数据库 · 建筑 · 发展 · 故障排除
______________________________________________________________________
入门指南
运行时间:节点18+
git clone
cd hivebrain
./setup.sh安装脚本处理一切:
- 安装HiveBrain和MCP服务器依赖项
- 编译MCP服务器(TypeScript→ JavaScript)
- 寄存器
hivebrain在克劳德代码的~/.claude/settings.json - 创建launchd plist以在登录时自动启动(macOS)
- 从HiveBrain开始
localhost:4321
打开一个新的Claude Code会话。 hivebrain_search, hivebrain_submit,以及 hivebrain_get 可作为本地工具使用。
已有的~/.claude/settings.json? 安装脚本会合并——它只会触及mcpServers.hivebrain钥匙。您现有的插件、钩子和设置未受影响。跑步setup.sh两次是安全的(幂等)。
你需要什么
| 要求 | 为了什么 |
|---|---|
| Node.js 18+ | 一切 |
| 克劳德代码 | MCP工具(web UI和API在没有它的情况下工作) |
| macOS | 通过launchd自动启动(在Linux上,手动启动或编写systemd单元) |
| 码头工人 | 仅用于运行测试套件 |
建筑
┌──────────────────────────────────────────────────┐
│ Your Machine │
│ │
│ ┌─────────────┐ ┌─────────────────────┐ │
│ │ Claude Code │◄──MCP──►│ MCP Server (stdio) │ │
│ │ Session │ │ hivebrain_search │ │
│ │ │ │ hivebrain_submit │ │
│ │ │ │ hivebrain_get │ │
│ └─────────────┘ └────────┬────────────┘ │
│ │ HTTP │
│ ▼ │
│ ┌────────────────┐ │
│ ┌─────────────┐ │ Astro Server │ │
│ │ Browser UI │◄──HTTP──│ localhost:4321│ │
│ │ localhost:4321│ │ │ │
│ └─────────────┘ └───────┬────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ SQLite │ │
│ │ FTS5 + WAL │ │
│ │ hivebrain.db │ │
│ └──────────────┘ │
└──────────────────────────────────────────────────┘MCP服务器 通过stdio(模型上下文协议)与Claude Code通信。它将工具调用转换为对Astro-dev服务器的HTTP请求,该服务器读取/写入SQLite数据库。浏览器UI直接点击相同的Astro服务器。一切都是本地的——没有网络呼叫离开你的机器。
API 参考
基本URL: http://localhost:4321
所有端点返回 Content-Type: application/json.空白字段(null, [], "")从响应中剥离以最小化有效载荷大小。
______________________________________________________________________
GET /api/search
对所有条目进行全文搜索。
参数
| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
q | string | 是 | 搜索查询--错误消息、概念、工具名称 |
full | "true" | 否 | 返回完整的条目,而不是紧凑的结果 |
响应(紧凑模式)
{
"query": "react hydration",
"count": 2,
"results": [
{
"id": 11,
"title": "Fix: React hydration mismatch errors",
"category": "gotcha",
"language": "javascript",
"framework": "react",
"severity": "major",
"tags": ["react", "ssr", "hydration", "nextjs", "remix"],
"error_messages": ["Hydration failed because the initial UI does not match"],
"problem_snippet": "React throws 'Hydration failed because the initial UI does not match...",
"url": "/api/entry/11"
}
],
"hint": "Use /api/entry/{id} for full details. Add &full=true to get complete entries inline."
}答复(full=true)
返回完整条目对象的平面数组。看 入口对象 对于完整的形状。
[
{
"id": 11,
"title": "Fix: React hydration mismatch errors",
"category": "gotcha",
"tags": ["react", "ssr", "hydration", "nextjs", "remix", "..."],
"problem": "React throws 'Hydration failed because...' (full text)",
"solution": "Multiple strategies depending on the cause... (full text)",
"why": "React SSR hydration works by comparing...",
"gotchas": ["useEffect runs ONLY on the client...", "..."],
"error_messages": ["Hydration failed because the initial UI does not match", "..."],
"keywords": ["server-side-rendering", "..."],
"language": "javascript",
"framework": "react",
"severity": "major",
"environment": ["browser", "nodejs", "ssr"],
"created_at": 1771789802
}
]状态代码: 200 成功, 400 缺失 q 参数, 500 内部错误。
______________________________________________________________________
GET /api/entry/:id
按ID获取单个条目。
参数
| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
id | integer | 是 | 条目ID(路径参数) |
fields | string | 没有 | 要返回的逗号分隔的字段名。 id 和 title 总是包括在内。 |
响应
返回完整 入口对象.
答复(附 ?fields=solution,gotchas)
{
"id": 11,
"title": "Fix: React hydration mismatch errors",
"solution": "Multiple strategies depending on the cause...",
"gotchas": ["useEffect runs ONLY on the client...", "..."]
}状态代码: 200 成功, 400 ID无效, 404 未找到, 500 内部错误。
______________________________________________________________________
GET /api/entries
列出和筛选条目。支持基于偏移量和基于光标的分页。
参数
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
category | string | -- | 筛选器: pattern, gotcha, principle, snippet, debug |
tag | string | -- | 按精确标签匹配进行筛选 |
language | string | -- | 筛选器: python, javascript, typescript, rust, go, java, c, cpp, csharp, ruby, php, swift, kotlin, sql, css, html, bash, yaml, toml, shell |
framework | string | -- | 筛选器: react, nextjs, remix, vue, nuxt, svelte, sveltekit, angular, django, flask, fastapi, express, nestjs, hono, fastify, rails, spring, laravel, gin, echo, actix, astro, gatsby, eleventy, hugo, playwright, jest, pytest, vitest, cypress, docker, kubernetes, terraform, tailwind, bootstrap, prisma, drizzle, sequelize, sqlalchemy, git |
severity | string | -- | 筛选器: critical, major, moderate, minor, tip |
environment | string | -- | 筛选器: macos, linux, windows, docker, ci-cd, browser, nodejs, ssr, edge, mobile, terminal, claude-code, ide, editor |
limit | integer | 50 | 每页最大结果数 |
offset | integer | 0 | 跳过N个结果(偏移分页) |
cursor | integer | -- | 来自的条目ID next_cursor (光标分页——大型数据集首选) |
full | "true" | -- | 返回完整的条目,而不是紧凑的条目 |
stats | "true" | -- | 包含聚合统计对象 |
响应(紧凑模式)
{
"count": 3,
"entries": [
{
"id": 11,
"title": "Fix: React hydration mismatch errors",
"category": "gotcha",
"language": "javascript",
"framework": "react",
"severity": "major",
"tags": ["react", "ssr", "hydration", "nextjs", "remix"],
"problem_snippet": "React throws 'Hydration failed because the initial UI does not match...",
"url": "/api/entry/11"
}
],
"next_cursor": 8,
"hint": "Use /api/entry/{id} for full details. Add &full=true to get complete entries inline."
}next_cursor 仅在有更多结果时才存在。将其传递为 ?cursor=8 以获取下一页。
答复(stats=true) 添加:
{
"stats": {
"total": 15,
"byCategory": [{ "category": "gotcha", "count": 6 }, "..."],
"tagCounts": { "react": 3, "python": 4, "..." : "..." },
"languageCounts": { "javascript": 5, "python": 4 },
"frameworkCounts": { "react": 3, "playwright": 2 },
"severityCounts": { "major": 4, "moderate": 6 },
"environmentCounts": { "macos": 5, "nodejs": 4 }
}
}状态代码: 200 成功, 400 无效参数, 500 内部错误。
______________________________________________________________________
POST /api/submit
创建新条目。价格限制为 每小时10个请求 每个IP。
请求体
{
"title": "SQLite FTS5 tokenizer ignores hyphens in compound words",
"category": "gotcha",
"problem": "Searching for 'server-side' in FTS5 matches 'server' and 'side' separately but not the compound term, leading to false positives.",
"solution": "Use phrase queries with double quotes in FTS5: '\"server side\"' (without hyphen). For exact hyphenated matching, add a LIKE fallback layer that searches raw text.",
"severity": "moderate",
"tags": ["sqlite", "fts5", "search", "text-processing"],
"keywords": ["tokenizer", "hyphen", "compound words", "phrase query", "full text search"],
"error_messages": [],
"language": "sql",
"why": "FTS5's default tokenizer splits on all non-alphanumeric characters.",
"gotchas": ["This also affects underscores and dots in version numbers"],
"environment": ["nodejs"],
"context": "When building search features on top of SQLite FTS5",
"version_info": "SQLite 3.35+",
"code_snippets": [
{
"code": "SELECT * FROM entries_fts WHERE entries_fts MATCH '\"server side\"'",
"lang": "sql",
"description": "Phrase query that matches the compound term"
}
],
"related_entries": [3, 7]
}必填字段
| 字段 | 类型 | 约束 | ||||
|---|---|---|---|---|---|---|
title | string | 最少10个字符 | ||||
category | string | "pattern" | "gotcha" | "principle" | "snippet" | "debug" |
problem | string | 最少50个字符 | ||||
solution | string | 最少80个字符 | ||||
severity | string | "critical" | "major" | "moderate" | "minor" | "tip" |
tags | string[] | 最少3个项目 | ||||
keywords | string[] | 最少3个项目——标签之外的搜索词(同义词、相关概念) | ||||
error_messages | string[] | 必需的 为了 gotcha 和 debug 类别。精确的错误字符串。 |
可选字段
| 字段 | 类型 | 描述 |
|---|---|---|
language | string | 主要语言(见 GET /api/entries 对于有效值) |
framework | string | 框架(如相关)(见 GET /api/entries 对于有效值) |
why | string | 根本原因解释 |
gotchas | string[] | 边缘案例,常见错误 |
environment | string[] | 如果适用(参见 GET /api/entries 对于有效值) |
context | string | 当这种情况发生时: "during deployment", "at build time" |
version_info | string | 版本约束: "React 18+", "Python 3.10+" |
code_snippets | object[] | 数组 { code: string, lang?: string, description?: string } |
related_entries | integer[] | 相关条目的ID |
learned_from | string | 这是在哪里发现的 |
submitted_by | string | 谁提交了此内容(默认值: "anonymous") |
响应(成功-- 201)
{
"id": 16,
"status": "created",
"url": "/api/entry/16",
"warnings": [
{ "field": "why", "suggestion": "Explain the root cause. Makes the entry much more useful." }
]
}警告是改进条目的非阻塞建议。无论如何都会创建条目。
响应(验证错误-- 400)
{
"error": "Submission rejected",
"issues": [
{ "field": "title", "issue": "Required, min 10 chars. Current: 5" },
{ "field": "tags", "issue": "Min 3 tags required (got 1). Include: language, topic, tools." }
],
"warnings": [
{ "field": "why", "suggestion": "Explain the root cause. Makes the entry much more useful." }
],
"hint": "Focus on metadata: tags, keywords, error_messages. These make entries findable.",
"token_budget": {
"problem": "50-300 chars",
"solution": "80-500 chars",
"tags": "3+ strings",
"keywords": "3+ strings (search terms beyond tags)",
"error_messages": "exact error strings (required for gotcha/debug)"
}
}状态代码: 201 创建, 400 验证错误, 429 速率受限, 500 内部错误。
______________________________________________________________________
入口对象
返回的条目的完整形状 GET /api/entry/:id 以及全模式响应。值为空的字段(null, [], "")省略。
| 字段 | 类型 | 描述 |
|---|---|---|
id | integer | 自动递增主键 |
title | string | 描述性标题 |
category | string | pattern, gotcha, principle, snippet, debug |
tags | string[] | 可搜索标签 |
problem | string | 出了什么问题 |
solution | string | 如何修复它 |
why | string | 根本原因解释 |
gotchas | string[] | 边缘案例和常见错误 |
error_messages | string[] | 搜索匹配的精确错误字符串 |
keywords | string[] | 标签之外的其他搜索词 |
language | string | 主要编程语言 |
framework | string | 框架(如适用) |
severity | string | critical, major, moderate, minor, tip |
environment | string[] | 在适用的情况下(macos, docker, ci-cd等等) |
context | string | 何时/何地发生 |
version_info | string | 版本约束 |
code_snippets | object[] | { code, lang?, description? } 物体 |
related_entries | integer[] | 相关条目的ID |
learned_from | string | 起源背景 |
submitted_by | string | 作者(默认值: "anonymous") |
created_at | integer | Unix时间戳 |
upvotes | integer | 社区投票(在以下情况下省略 0) |
______________________________________________________________________
MCP工具
MCP服务器通过stdio向Claude Code公开了三个工具。之后 setup.sh,他们出现在每一次会议上。
hivebrain_search
搜索知识库。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
query | string | 是 | 错误消息、概念、工具名称 |
返回格式化的markdown,其中包含每个匹配的完整条目详细信息。如果HiveBrain脱机,则返回一条有用的错误消息(不是崩溃)。
hivebrain_submit
提交新条目。接受与相同的字段 POST /api/submit --看 提交参赛作品 对于完整的模式。成功或发生结构化验证错误时返回创建的条目ID。
hivebrain_get
按ID获取完整条目。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
id | integer | 是 | 条目ID |
返回带所有输入字段的格式化markdown。
离线处理
这三个工具都能捕获连接错误并返回描述性消息:
- 连接被拒绝 →
"HiveBrain is offline. Start it with: cd ~/local_AI/hivebrain && npm run dev" - 超时(5s) →
"HiveBrain is not responding (timeout). Is it running at localhost:4321?"
教克劳德何时使用它们
添加以下内容 CLAUDE_SNIPPET.md 到你的项目 CLAUDE.md。这句话告诉克劳德:
- 搜索 遇到不熟悉的错误、调试或进入不熟悉的代码库区域时
- 提交 在解决了非琐碎的错误、发现了陷阱或建立了可重用的模式之后
- 不要提交 琐碎的修复、明显的解决方案或一次性的配置更改
搜索工作原理
搜索不是单个查询。这是一个多层排名系统,结合了独立策略的结果,对其进行评分,并返回最佳匹配。
图层(按优先级顺序)
| 图层 | 策略 | 得分 | 详细信息 |
|---|---|---|---|
| 1a | FTS5与查询(精确术语) | 100 | "react" AND "hydration" --最高精度 |
| 1b | FTS5与同义词扩展 | 95 | ("js" OR "javascript") AND "hydration" |
| 1c | FTS5前缀AND | 85 | react* AND hydrat* --部分单词匹配 |
| 1d | FTS5单词+同义词 | 90/85 | 用于单字查询 |
| 1e | FTS5或回退 | 20–45 | 仅当AND产生\<3个结果时。按比赛比例得分。 |
| 2 | 精确标签匹配 | 30–80 | 每个术语,根据标签/关键字/元之间匹配的术语数量进行评分 |
| 3 | 语言/框架列 | 30-80 | 与标签相同的多术语评分 |
| 4 | 错误消息子字符串 | 75–90 | LIKE '%error string%' --对粘贴错误至关重要 |
| 5 | 关键字+环境匹配 | 30–80 | JSON数组搜索 |
| 6 | 广泛的LIKE回退 | 30 | 最后的手段,只有当上述所有结果小于3时才会触发 |
后期处理
- 去重 --来自多层的同一条目保持最高分数
- 标题提升 --标题中出现搜索词的条目得分为+15
- 噪声过滤 --得分低于最高结果40%的结果将被删除
- 限制 --最多50个结果,按分数降序排列
同义词扩展
内置同义词映射处理常见缩写:
| 输入 | 也匹配 |
|---|---|
js | javascript |
ts | typescript |
py | python |
k8s | kubernetes |
next | nextjs, next.js |
node | nodejs, node.js |
auth | authentication, authorization |
db | database |
ssr | server side rendering |
ci | continuous integration |
完整列表:40多个映射 src/lib/db.ts.
FTS5字段权重
BM25评分(自定义权重越高=越重要):
| 字段 | 重量 |
|---|---|
title | 10.0 |
problem | 5.0 |
solution | 5.0 |
why | 2.0 |
error_messages | 3.0 |
keywords | 3.0 |
context | 2.0 |
tags | 4.0 |
language | 4.0 |
framework | 4.0 |
数据库
带WAL模式的SQLite。储存于 db/hivebrain.db.
模式
CREATE TABLE entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
category TEXT NOT NULL CHECK(category IN ('pattern','gotcha','principle','snippet','debug')),
tags TEXT NOT NULL DEFAULT '[]', -- JSON string[]
problem TEXT NOT NULL,
solution TEXT NOT NULL,
why TEXT,
gotchas TEXT DEFAULT '[]', -- JSON string[]
learned_from TEXT,
submitted_by TEXT DEFAULT 'anonymous',
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
upvotes INTEGER DEFAULT 0,
language TEXT,
framework TEXT,
severity TEXT DEFAULT 'moderate' CHECK(severity IN ('critical','major','moderate','minor','tip')),
environment TEXT DEFAULT '[]', -- JSON string[]
error_messages TEXT DEFAULT '[]', -- JSON string[]
keywords TEXT DEFAULT '[]', -- JSON string[]
context TEXT,
code_snippets TEXT DEFAULT '[]', -- JSON {code,lang?,description?}[]
related_entries TEXT DEFAULT '[]', -- JSON integer[]
version_info TEXT
);索引
idx_entries_category--快速类别过滤idx_entries_language--快速语言过滤idx_entries_framework--快速框架过滤idx_entries_severity--快速严重性过滤idx_entries_created_at--按时间顺序排列
FTS5虚拟桌
entries_fts 索引10个字段进行全文搜索。通过自动同步 AFTER INSERT, AFTER UPDATE,以及 AFTER DELETE 触发器——无需手动重新索引。
种子数据
npm run seed项目结构
hivebrain/
├── src/
│ ├── pages/
│ │ ├── index.astro # Web UI — browse, search, filter
│ │ ├── entry/[id].astro # Entry detail page
│ │ └── api/
│ │ ├── search.ts # GET /api/search
│ │ ├── submit.ts # POST /api/submit (validation + rate limiting)
│ │ ├── entries.ts # GET /api/entries (list + filter + paginate)
│ │ └── entry/[id].ts # GET /api/entry/:id (detail + field filtering)
│ ├── components/
│ │ ├── Header.astro
│ │ ├── SearchBar.astro
│ │ ├── FilterBar.astro
│ │ ├── EntryCard.astro
│ │ └── Stats.astro
│ └── lib/
│ ├── db.ts # SQLite connection, queries, multi-layer FTS5 search
│ └── api-utils.ts # JSON responses, field parsing, token-efficient stripping
├── db/
│ ├── schema.sql # Table + FTS5 + triggers + indexes
│ ├── seed.js # Seed data
│ ├── hivebrain.db # SQLite database (WAL mode)
│ └── migrate-*.js # Migration scripts
├── mcp-server/
│ ├── index.ts # MCP server — 3 tools over stdio
│ ├── package.json # @modelcontextprotocol/sdk, zod
│ ├── tsconfig.json
│ └── dist/ # Compiled output (generated by npm run build)
├── setup.sh # One-command setup for new users
├── CLAUDE_SNIPPET.md # Ready-to-copy CLAUDE.md instructions
├── Dockerfile.test # Clean test environment
└── test-setup.sh # Automated test suite (Docker)发展
npm run dev # Start dev server at localhost:4321
npm run build # Production build to ./dist/
npm run preview # Preview production build
npm run seed # Populate database with example entriesMCP服务器
cd mcp-server
npm install # Install MCP SDK + zod
npm run build # Compile TypeScript to dist/
npm start # Run standalone (for testing)手动MCP协议测试
printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0.0"}}}\n' \
| node mcp-server/dist/index.js应返回 {"result":{"protocolVersion":"2024-11-05","capabilities":{"tools":{"listChanged":true}},"serverInfo":{"name":"hivebrain","version":"1.0.0"}},"jsonrpc":"2.0","id":1}.
自动启动(macOS)
setup.sh 在以下位置创建launchd plist ~/Library/LaunchAgents/com.local.hivebrain.plist:
- 登录时启动HiveBrain
- 崩溃时重新启动(
KeepAlive: true) - 将stdout和stderr记录到
/tmp/hivebrain.log
手动控制
# Stop
launchctl unload ~/Library/LaunchAgents/com.local.hivebrain.plist
# Start
launchctl load ~/Library/LaunchAgents/com.local.hivebrain.plist
# Check status
launchctl list | grep hivebrain
# Tail logs
tail -f /tmp/hivebrain.logLinux
没有洗衣房。创建systemd单元或手动启动:
cd hivebrain && npm run dev测试
在干净的Docker容器中运行完整的测试套件:
./test-setup.sh建筑来自 node:22-slim +Claude Code(未预装其他任何东西)并验证:
| 测试 | 它检查什么 |
|---|---|
| 白板 | 否 ~/.claude 安装前目录已存在 |
| 安装完成 | setup.sh 在新机器上退出0 |
| MCP服务器编译 | dist/index.js 构建后存在 |
| 已创建设置 | ~/.claude/settings.json 使用有效的JSON从头开始创建 |
| MCP协议 | 服务器响应 initialize 握手 |
| 所有工具已注册 | hivebrain_search, hivebrain_submit, hivebrain_get 在 tools/list |
| 离线处理 | HiveBrain关闭时返回有用错误 |
| API工程 | GET /api/search 和 GET /api/entry/:id 正确回答 |
| 端到端 | MCP工具调用实时HiveBrain并返回数据 |
| Idempotent | 重新运行 setup.sh 不重复配置条目 |
| 设置合并 | 现有 settings.json 添加hivebrain时保留配置 |
故障排除
HiveBrain无法启动
# Check if port 4321 is in use
lsof -i :4321
# Check launchd status
launchctl list | grep hivebrain
# Check logs
tail -50 /tmp/hivebrain.log
# Manual start (bypass launchd)
cd hivebrain && npm run devMCP工具未出现在Claude代码中
# Verify settings.json has the entry
cat ~/.claude/settings.json | grep hivebrain
# Verify the built file exists
ls -la hivebrain/mcp-server/dist/index.js
# Test the MCP server manually
printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0.0"}}}\n' \
| node hivebrain/mcp-server/dist/index.js启动Claude Code时加载MCP服务器。 您必须打开一个新会话 运行后 setup.sh.
搜索未返回任何结果
# Check if the database has entries
sqlite3 db/hivebrain.db "SELECT count(*) FROM entries;"
# Check if FTS index is populated
sqlite3 db/hivebrain.db "SELECT count(*) FROM entries_fts;"
# If FTS is empty, rebuild it
sqlite3 db/hivebrain.db "INSERT INTO entries_fts(entries_fts) VALUES('rebuild');"
# Seed example data
npm run seed提交时价格有限
提交端点允许 每小时10个请求 每个IP。等待窗口重置,或重新启动服务器以清除内存中的计数器。
数据库锁定错误
SQLite处于WAL模式,支持并发读取+一个写入器。如果你看到 SQLITE_BUSY:
# Check for lingering connections
lsof db/hivebrain.db
# WAL checkpoint (merges WAL back into main db)
sqlite3 db/hivebrain.db "PRAGMA wal_checkpoint(TRUNCATE);"