@hsingjui/contextweaver 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 hsingjui
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,380 @@
1
+ # ContextWeaver
2
+
3
+ <p align="center">
4
+ <strong>🧵 为 AI Agent 精心编织的代码库上下文引擎</strong>
5
+ </p>
6
+
7
+ <p align="center">
8
+ <em>Semantic Code Retrieval for AI Agents — Hybrid Search • Graph Expansion • Token-Aware Packing</em>
9
+ </p>
10
+
11
+ ---
12
+
13
+ **ContextWeaver** 是一个专为 AI 代码助手设计的语义检索引擎,采用混合搜索(向量 + 词法)、智能上下文扩展和 Token 感知打包策略,为 LLM 提供精准、相关且上下文完整的代码片段。
14
+
15
+ ## ✨ 核心特性
16
+
17
+ ### 🔍 混合检索引擎
18
+ - **向量召回 (Vector Retrieval)**:基于语义相似度的深度理解
19
+ - **词法召回 (Lexical/FTS)**:精确匹配函数名、类名等技术术语
20
+ - **RRF 融合 (Reciprocal Rank Fusion)**:智能融合多路召回结果
21
+
22
+ ### 🧠 AST 语义分片
23
+ - **Tree-sitter 解析**:支持 TypeScript、JavaScript、Python、Go、Java、Rust 六大语言
24
+ - **Dual-Text 策略**:`displayCode` 用于展示,`vectorText` 用于 Embedding
25
+ - **Gap-Aware 合并**:智能处理代码间隙,保持语义完整性
26
+ - **Breadcrumb 注入**:向量文本包含层级路径,提升检索召回率
27
+
28
+ ### 📊 三阶段上下文扩展
29
+ - **E1 邻居扩展**:同文件前后相邻 chunks,保证代码块完整性
30
+ - **E2 面包屑补全**:同一类/函数下的其他方法,理解整体结构
31
+ - **E3 Import 解析**:跨文件依赖追踪(可配置开关)
32
+
33
+ ### 🎯 智能截断策略 (Smart TopK)
34
+ - **Anchor & Floor**:动态阈值 + 绝对下限双保险
35
+ - **Delta Guard**:防止 Top1 outlier 场景的误判
36
+ - **Safe Harbor**:前 N 个结果只检查下限,保证基本召回
37
+
38
+ ### 🔌 MCP 原生支持
39
+ - **MCP Server 模式**:一键启动 Model Context Protocol 服务端
40
+ - **Zen Design 理念**:意图与术语分离,LLM 友好的 API 设计
41
+ - **自动索引**:首次查询自动触发索引,增量更新透明无感
42
+
43
+ ## 📦 快速开始
44
+
45
+ ### 环境要求
46
+
47
+ - Node.js >= 20
48
+ - pnpm (推荐) 或 npm
49
+
50
+ ### 安装
51
+
52
+ ```bash
53
+ # 全局安装
54
+ npm install -g contextweaver
55
+
56
+ # 或使用 pnpm
57
+ pnpm add -g contextweaver
58
+ ```
59
+
60
+ ### 初始化配置
61
+
62
+ ```bash
63
+ # 初始化配置文件(创建 ~/.contextweaver/.env)
64
+ contextweaver init
65
+ # 或简写
66
+ cw init
67
+ ```
68
+
69
+ 编辑 `~/.contextweaver/.env`,填入你的 API Key:
70
+
71
+ ```bash
72
+ # Embedding API 配置(必需)
73
+ EMBEDDINGS_API_KEY=your-api-key-here
74
+ EMBEDDINGS_BASE_URL=https://api.siliconflow.cn/v1/embeddings
75
+ EMBEDDINGS_MODEL=BAAI/bge-m3
76
+ EMBEDDINGS_MAX_CONCURRENCY=10
77
+ EMBEDDINGS_DIMENSIONS=1024
78
+
79
+ # Reranker 配置(必需)
80
+ RERANK_API_KEY=your-api-key-here
81
+ RERANK_BASE_URL=https://api.siliconflow.cn/v1/rerank
82
+ RERANK_MODEL=BAAI/bge-reranker-v2-m3
83
+ RERANK_TOP_N=20
84
+
85
+ # 忽略模式(可选,逗号分隔)
86
+ # IGNORE_PATTERNS=.venv,node_modules
87
+ ```
88
+
89
+ ### 索引代码库
90
+
91
+ ```bash
92
+ # 在代码库根目录执行
93
+ contextweaver index
94
+
95
+ # 指定路径
96
+ contextweaver index /path/to/your/project
97
+
98
+ # 强制重新索引
99
+ contextweaver index --force
100
+ ```
101
+
102
+ ### 本地搜索
103
+
104
+ ```bash
105
+ # 语义搜索
106
+ cw search --information-request "用户认证流程是如何实现的?"
107
+
108
+ # 带精确术语
109
+ cw search --information-request "数据库连接逻辑" --technical-terms "DatabasePool,Connection"
110
+ ```
111
+
112
+ ### 启动 MCP 服务器
113
+
114
+ ```bash
115
+ # 启动 MCP 服务端(供 Claude 等 AI 助手使用)
116
+ contextweaver mcp
117
+ ```
118
+
119
+ ## 🔧 MCP 集成配置
120
+
121
+ ### Claude Desktop 配置
122
+
123
+ 在 Claude Desktop 的配置文件中添加:
124
+
125
+ ```json
126
+ {
127
+ "mcpServers": {
128
+ "contextweaver": {
129
+ "command": "contextweaver",
130
+ "args": ["mcp"]
131
+ }
132
+ }
133
+ }
134
+ ```
135
+
136
+ ### MCP 工具说明
137
+
138
+ ContextWeaver 提供一个核心 MCP 工具:`codebase-retrieval`
139
+
140
+ #### 参数说明
141
+
142
+ | 参数 | 类型 | 必需 | 描述 |
143
+ |------|------|------|------|
144
+ | `repo_path` | string | ✅ | 代码库根目录的绝对路径 |
145
+ | `information_request` | string | ✅ | 自然语言形式的语义意图描述 |
146
+ | `technical_terms` | string[] | ❌ | 精确技术术语(类名、函数名等) |
147
+
148
+ #### 设计理念 (Zen Design)
149
+
150
+ - **意图与术语分离**:`information_request` 描述「做什么」,`technical_terms` 过滤「叫什么」
151
+ - **黄金默认值**:提供同文件上下文,禁止默认跨文件抓取
152
+ - **回归代理本能**:工具只负责定位,跨文件探索由 Agent 自主发起
153
+
154
+ ## 🏗️ 架构设计
155
+
156
+ ```mermaid
157
+ flowchart TB
158
+ subgraph Interface["CLI / MCP Interface"]
159
+ CLI[contextweaver CLI]
160
+ MCP[MCP Server]
161
+ end
162
+
163
+ subgraph Search["SearchService"]
164
+ VR[Vector Retrieval]
165
+ LR[Lexical Retrieval]
166
+ RRF[RRF Fusion + Rerank]
167
+ VR --> RRF
168
+ LR --> RRF
169
+ end
170
+
171
+ subgraph Expand["Context Expansion"]
172
+ GE[GraphExpander]
173
+ CP[ContextPacker]
174
+ GE --> CP
175
+ end
176
+
177
+ subgraph Storage["Storage Layer"]
178
+ VS[(VectorStore<br/>LanceDB)]
179
+ DB[(SQLite<br/>FTS5)]
180
+ end
181
+
182
+ subgraph Index["Indexing Pipeline"]
183
+ CR[Crawler<br/>fdir] --> SS[SemanticSplitter<br/>Tree-sitter] --> IX[Indexer<br/>Batch Embedding]
184
+ end
185
+
186
+ Interface --> Search
187
+ RRF --> GE
188
+ Search <--> Storage
189
+ Expand <--> Storage
190
+ Index --> Storage
191
+ ```
192
+
193
+ ### 核心模块说明
194
+
195
+ | 模块 | 职责 |
196
+ |------|------|
197
+ | **SearchService** | 混合搜索核心,协调向量/词法召回、RRF 融合、Rerank 精排 |
198
+ | **GraphExpander** | 上下文扩展器,执行 E1/E2/E3 三阶段扩展策略 |
199
+ | **ContextPacker** | 上下文打包器,负责段落合并和 Token 预算控制 |
200
+ | **VectorStore** | LanceDB 适配层,管理向量索引的增删改查 |
201
+ | **SQLite (FTS5)** | 元数据存储 + 全文搜索索引 |
202
+ | **SemanticSplitter** | AST 语义分片器,基于 Tree-sitter 解析 |
203
+
204
+ ## 📁 项目结构
205
+
206
+ ```
207
+ contextweaver/
208
+ ├── src/
209
+ │ ├── index.ts # CLI 入口
210
+ │ ├── config.ts # 配置管理(环境变量)
211
+ │ ├── api/ # 外部 API 封装
212
+ │ │ ├── embed.ts # Embedding API
213
+ │ │ └── rerank.ts # Reranker API
214
+ │ ├── chunking/ # 语义分片
215
+ │ │ ├── SemanticSplitter.ts # AST 语义分片器
216
+ │ │ ├── SourceAdapter.ts # 源码适配器
217
+ │ │ ├── LanguageSpec.ts # 语言规范定义
218
+ │ │ └── ParserPool.ts # Tree-sitter 解析器池
219
+ │ ├── scanner/ # 文件扫描
220
+ │ │ ├── crawler.ts # 文件系统遍历
221
+ │ │ ├── processor.ts # 文件处理
222
+ │ │ └── filter.ts # 过滤规则
223
+ │ ├── indexer/ # 索引器
224
+ │ │ └── index.ts # 批量索引逻辑
225
+ │ ├── vectorStore/ # 向量存储
226
+ │ │ └── index.ts # LanceDB 适配层
227
+ │ ├── db/ # 数据库
228
+ │ │ └── index.ts # SQLite + FTS5
229
+ │ ├── search/ # 搜索服务
230
+ │ │ ├── SearchService.ts # 核心搜索服务
231
+ │ │ ├── GraphExpander.ts # 上下文扩展器
232
+ │ │ ├── ContextPacker.ts # 上下文打包器
233
+ │ │ ├── fts.ts # 全文搜索
234
+ │ │ ├── config.ts # 搜索配置
235
+ │ │ ├── types.ts # 类型定义
236
+ │ │ └── resolvers/ # 多语言 Import 解析器
237
+ │ │ ├── JsTsResolver.ts
238
+ │ │ ├── PythonResolver.ts
239
+ │ │ ├── GoResolver.ts
240
+ │ │ ├── JavaResolver.ts
241
+ │ │ └── RustResolver.ts
242
+ │ ├── mcp/ # MCP 服务端
243
+ │ │ ├── server.ts # MCP 服务器实现
244
+ │ │ ├── main.ts # MCP 入口
245
+ │ │ └── tools/
246
+ │ │ └── codebaseRetrieval.ts # 代码检索工具
247
+ │ └── utils/ # 工具函数
248
+ │ └── logger.ts # 日志系统
249
+ ├── package.json
250
+ └── tsconfig.json
251
+ ```
252
+
253
+ ## ⚙️ 配置详解
254
+
255
+ ### 环境变量
256
+
257
+ | 变量名 | 必需 | 默认值 | 描述 |
258
+ |--------|------|--------|------|
259
+ | `EMBEDDINGS_API_KEY` | ✅ | - | Embedding API 密钥 |
260
+ | `EMBEDDINGS_BASE_URL` | ✅ | - | Embedding API 地址 |
261
+ | `EMBEDDINGS_MODEL` | ✅ | - | Embedding 模型名称 |
262
+ | `EMBEDDINGS_MAX_CONCURRENCY` | ❌ | 10 | Embedding 并发数 |
263
+ | `EMBEDDINGS_DIMENSIONS` | ❌ | 1024 | 向量维度 |
264
+ | `RERANK_API_KEY` | ✅ | - | Reranker API 密钥 |
265
+ | `RERANK_BASE_URL` | ✅ | - | Reranker API 地址 |
266
+ | `RERANK_MODEL` | ✅ | - | Reranker 模型名称 |
267
+ | `RERANK_TOP_N` | ❌ | 20 | Rerank 返回数量 |
268
+ | `IGNORE_PATTERNS` | ❌ | - | 额外忽略模式 |
269
+
270
+ ### 搜索配置参数
271
+
272
+ ```typescript
273
+ interface SearchConfig {
274
+ // === 召回阶段 ===
275
+ vectorTopK: number; // 向量召回数量(默认 30)
276
+ vectorTopM: number; // 送入融合的向量结果数(默认 30)
277
+ ftsTopKFiles: number; // FTS 召回文件数(默认 15)
278
+ lexChunksPerFile: number; // 每文件词法 chunks 数(默认 3)
279
+ lexTotalChunks: number; // 词法总 chunks 数(默认 30)
280
+
281
+ // === 融合阶段 ===
282
+ rrfK0: number; // RRF 平滑常数(默认 60)
283
+ wVec: number; // 向量权重(默认 1.0)
284
+ wLex: number; // 词法权重(默认 0.5)
285
+ fusedTopM: number; // 融合后送 rerank 数量(默认 40)
286
+
287
+ // === Rerank ===
288
+ rerankTopN: number; // Rerank 后保留数量(默认 10)
289
+ maxRerankChars: number; // Rerank 文本最大字符数(默认 1200)
290
+
291
+ // === 扩展策略 ===
292
+ neighborHops: number; // E1 邻居跳数(默认 2)
293
+ breadcrumbExpandLimit: number; // E2 面包屑补全数(默认 3)
294
+ importFilesPerSeed: number; // E3 每 seed 导入文件数(默认 0)
295
+ chunksPerImportFile: number; // E3 每导入文件 chunks(默认 0)
296
+
297
+ // === Smart TopK ===
298
+ enableSmartTopK: boolean; // 启用智能截断(默认 true)
299
+ smartTopScoreRatio: number; // 动态阈值比例(默认 0.5)
300
+ smartMinScore: number; // 绝对下限(默认 0.25)
301
+ smartMinK: number; // Safe Harbor 数量(默认 2)
302
+ smartMaxK: number; // 硬上限(默认 15)
303
+ }
304
+ ```
305
+
306
+ ## 🌍 多语言支持
307
+
308
+ ContextWeaver 通过 Tree-sitter 原生支持以下编程语言的 AST 解析:
309
+
310
+ | 语言 | AST 解析 | Import 解析 | 文件扩展名 |
311
+ |------|----------|-------------|-----------|
312
+ | TypeScript | ✅ | ✅ | `.ts`, `.tsx` |
313
+ | JavaScript | ✅ | ✅ | `.js`, `.jsx`, `.mjs` |
314
+ | Python | ✅ | ✅ | `.py` |
315
+ | Go | ✅ | ✅ | `.go` |
316
+ | Java | ✅ | ✅ | `.java` |
317
+ | Rust | ✅ | ✅ | `.rs` |
318
+
319
+ 其他语言会采用基于行的 Fallback 分片策略,仍可正常索引和搜索。
320
+
321
+ ## 🔄 工作流程
322
+
323
+ ### 索引流程
324
+
325
+ ```
326
+ 1. Crawler → 遍历文件系统,过滤忽略项
327
+ 2. Processor → 读取文件内容,计算 hash
328
+ 3. Splitter → AST 解析,语义分片
329
+ 4. Indexer → 批量 Embedding,写入向量库
330
+ 5. FTS Index → 更新全文搜索索引
331
+ ```
332
+
333
+ ### 搜索流程
334
+
335
+ ```
336
+ 1. Query Parse → 解析查询,分离语义和术语
337
+ 2. Hybrid Recall → 向量 + 词法双路召回
338
+ 3. RRF Fusion → Reciprocal Rank Fusion 融合
339
+ 4. Rerank → 交叉编码器精排
340
+ 5. Smart Cutoff → 智能分数截断
341
+ 6. Graph Expand → 邻居/面包屑/导入扩展
342
+ 7. Context Pack → 段落合并,Token 预算
343
+ 8. Format Output → 格式化返回给 LLM
344
+ ```
345
+
346
+ ## 📊 性能特性
347
+
348
+ - **增量索引**:只处理变更文件,二次索引速度提升 10x+
349
+ - **批量 Embedding**:自适应批次大小,支持并发控制
350
+ - **速率限制恢复**:429 错误时自动退避,渐进恢复
351
+ - **连接池复用**:Tree-sitter 解析器池化复用
352
+ - **文件索引缓存**:GraphExpander 文件路径索引 lazy load
353
+
354
+ ## 🐛 日志与调试
355
+
356
+ 日志文件位置:`~/.contextweaver/logs/app.YYYY-MM-DD.log`
357
+
358
+ 设置日志级别:
359
+
360
+ ```bash
361
+ # 开启 debug 日志
362
+ LOG_LEVEL=debug contextweaver search --information-request "..."
363
+ ```
364
+
365
+ ## 📄 开源协议
366
+
367
+ 本项目采用 MIT 许可证。
368
+
369
+ ## 🙏 致谢
370
+
371
+ - [Tree-sitter](https://tree-sitter.github.io/tree-sitter/) - 高性能语法解析
372
+ - [LanceDB](https://lancedb.com/) - 嵌入式向量数据库
373
+ - [MCP](https://modelcontextprotocol.io/) - Model Context Protocol
374
+ - [SiliconFlow](https://siliconflow.cn/) - 推荐的 Embedding/Reranker API 服务
375
+
376
+ ---
377
+
378
+ <p align="center">
379
+ <sub>Made with ❤️ for AI-assisted coding</sub>
380
+ </p>