shelfmark-rag 1.0.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lucas Santana
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.
@@ -0,0 +1,247 @@
1
+ Metadata-Version: 2.4
2
+ Name: shelfmark-rag
3
+ Version: 1.0.0
4
+ Summary: Local hybrid retrieval (BM25 + embeddings + RRF) for agent memory and codebases — one SQLite file, MCP server included.
5
+ Author: Lucas Santana
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Lucas Santana
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/LucasSantana-Dev/shelfmark
29
+ Project-URL: Repository, https://github.com/LucasSantana-Dev/shelfmark
30
+ Project-URL: Benchmark, https://github.com/LucasSantana-Dev/shelfmark/blob/main/BENCHMARK.md
31
+ Keywords: rag,retrieval,semantic-search,bm25,embeddings,mcp,agent-memory,hybrid-search
32
+ Classifier: Development Status :: 5 - Production/Stable
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: OS Independent
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3.10
38
+ Classifier: Programming Language :: Python :: 3.11
39
+ Classifier: Programming Language :: Python :: 3.12
40
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
41
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
42
+ Requires-Python: >=3.10
43
+ Description-Content-Type: text/markdown
44
+ License-File: LICENSE
45
+ Requires-Dist: numpy<3,>=1.26
46
+ Requires-Dist: PyYAML>=6.0
47
+ Requires-Dist: rank-bm25~=0.2
48
+ Requires-Dist: sentence-transformers~=5.5
49
+ Dynamic: license-file
50
+
51
+ # shelfmark
52
+
53
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
54
+ [![GitHub stars](https://img.shields.io/github/stars/LucasSantana-Dev/shelfmark?style=flat)](https://github.com/LucasSantana-Dev/shelfmark/stargazers)
55
+ [![MCP](https://img.shields.io/badge/MCP-server-6b5ce7)](https://modelcontextprotocol.io)
56
+
57
+ ![shelfmark: local hybrid retrieval for agent memory and codebases](.github/shelfmark-card.png)
58
+
59
+ Local hybrid retrieval for agent memory and codebases. One SQLite file, no
60
+ services, no cloud. BM25 + dense embeddings fused with Reciprocal Rank Fusion,
61
+ an optional cross-encoder reranker, and an MCP server so coding agents
62
+ (Claude Code, Codex, anything MCP) can recall your notes, decisions, docs, and
63
+ code instead of guessing.
64
+
65
+ A shelfmark is the code a librarian writes on a book so it can be found again.
66
+ That is the whole product: before your agent answers, the librarian fetches the
67
+ handful of notes and code chunks most likely to matter and puts them on the
68
+ desk.
69
+
70
+ **[Why this exists](#why-this-exists)** · **[Quickstart](#quickstart)** ·
71
+ **[MCP server](#mcp-server-agent-integration)** ·
72
+ **[What gets indexed](#what-gets-indexed)** · **[Evaluation](#evaluation)** ·
73
+ **[How it compares](#how-it-compares)** · **[Configuration](#configuration)**
74
+
75
+ ## Why this exists
76
+
77
+ Agent harnesses accumulate knowledge: memory notes, ADRs, plans, standards,
78
+ handoffs, and the code itself. The useful answer to most questions is already
79
+ written down somewhere. shelfmark indexes all of it into one local SQLite file
80
+ and answers "what did we decide about X / where did we handle Y" in a single
81
+ query, with `path:line` citations.
82
+
83
+ shelfmark is the retrieval engine that came out of a year of running AI coding
84
+ agents daily — most recently distilled from
85
+ [forgekit](https://github.com/LucasSantana-Dev/forgekit), an AI dev toolkit for
86
+ coding agents. Every design choice below was forced by a real failure mode in
87
+ that daily use, not picked off a paper.
88
+
89
+ Design choices that fell out of a year of measured iteration (see
90
+ `eval/holdout-policy.md` and inline rationale comments):
91
+
92
+ - **Hybrid by default.** BM25 catches identifiers and exact terms; embeddings
93
+ catch paraphrase. RRF fusion beats either alone on mixed corpora.
94
+ - **Code-aware tokenization.** camelCase/snake_case sub-tokens on both corpus
95
+ and query sides ("create player" matches `createPlayer`). Measured +2.8pp
96
+ code / +3.2pp overall.
97
+ - **Symbol-definition boost.** Chunks whose defined symbol matches a query
98
+ identifier get a rank-0 signal (+2.8pp code, zero regressions).
99
+ - **Selective reranking.** Cross-encoder rerank helps code and standards,
100
+ *hurts* memory recall (measured -10.5pp). The rerank policy is scope-aware;
101
+ memory is never reranked.
102
+ - **Contextual chunk prefixes.** Every chunk embeds with a
103
+ `type | repo | file | symbol` header, not raw text.
104
+ - **Freshness without wall-clock.** Optional recency prior for memory scope,
105
+ deterministic (reference = max mtime among candidates), so evals stay
106
+ reproducible.
107
+
108
+ ## Quickstart
109
+
110
+ ```bash
111
+ pip install shelfmark-rag # or: pipx install shelfmark-rag
112
+
113
+ shelfmark-build # first run writes a starter ~/.shelfmark/sources.yaml — edit it, then rerun
114
+ shelfmark-query "how do we handle retry timeouts"
115
+ ```
116
+
117
+ First build downloads `intfloat/multilingual-e5-small` (~120MB). Everything
118
+ after that runs offline.
119
+
120
+ <details>
121
+ <summary>Prefer a local checkout instead? (contributing, editing the source)</summary>
122
+
123
+ ```bash
124
+ git clone https://github.com/LucasSantana-Dev/shelfmark && cd shelfmark
125
+ python3 -m venv venv && venv/bin/pip install -e .
126
+
127
+ venv/bin/shelfmark-build
128
+ venv/bin/shelfmark-query "how do we handle retry timeouts"
129
+ ```
130
+
131
+ </details>
132
+
133
+ ## MCP server (agent integration)
134
+
135
+ ```jsonc
136
+ // e.g. Claude Code: .mcp.json or ~/.claude.json
137
+ {
138
+ "mcpServers": {
139
+ "shelfmark": {
140
+ "command": "shelfmark-mcp"
141
+ }
142
+ }
143
+ }
144
+ ```
145
+
146
+ (Local checkout instead of `pipx install`? Use `"command": "/path/to/shelfmark/venv/bin/shelfmark-mcp"`.)
147
+
148
+ Two tools:
149
+
150
+ - `rag_query` — full-corpus hybrid search (code, docs, commits, notes).
151
+ Auto-scopes to the repo your agent is working in.
152
+ - `search_knowledge` — cross-project search over durable knowledge only
153
+ (memory/standards/plans/handoffs/adrs; configurable via
154
+ `RAG_KNOWLEDGE_SCOPE`). Never reranked, by measurement.
155
+
156
+ `examples/claude-code/` has the full loop: auto-recall on every prompt
157
+ (UserPromptSubmit), incremental reindex on file writes (PostToolUse), drift
158
+ reindex + weekly report at session start, and a nightly rebuild with an eval
159
+ regression gate.
160
+
161
+ ## What gets indexed
162
+
163
+ `sources.yaml` declares everything (see `sources.yaml.example`):
164
+
165
+ | kind | what |
166
+ |------|------|
167
+ | `repos` | source code (py/ts/js/sh, symbol-aware chunking), `docs/**`, README, CHANGELOG, `docs/specs/**`, roadmap, last 180d of commit messages |
168
+ | `sources` | arbitrary markdown globs, each under a free `type` label you filter on at query time |
169
+ | `code_globs` | loose scripts outside any repo |
170
+
171
+ Incremental reindex (`indexer.py --incremental <files>`) keeps writes cheap;
172
+ `session_chunker.py` can additionally index agent session transcripts.
173
+
174
+ ## Evaluation
175
+
176
+ The eval harness is the part most RAG setups skip. `eval/run.py` scores
177
+ Hit@1/3/5 + MRR per scope against a JSONL dataset; `eval/check.sh` gates any
178
+ change at >5pp regression vs a frozen baseline; `eval/holdout-policy.md`
179
+ documents the train/holdout discipline (the holdout set is never used for
180
+ tuning — numbers quoted from it are honest).
181
+
182
+ This repo ships a public, reproducible dataset (`eval/dataset-public.jsonl`)
183
+ whose queries target this repository's own code and docs:
184
+
185
+ ```bash
186
+ venv/bin/python indexer.py # index this repo (sources.yaml.example works as-is)
187
+ venv/bin/python eval/run.py --dataset eval/dataset-public.jsonl --label mine
188
+ ```
189
+
190
+ Benchmark results and methodology: [BENCHMARK.md](BENCHMARK.md).
191
+
192
+ To evaluate on YOUR corpus, write ~50 `{"query", "expect_path_contains",
193
+ "expect_scope"}` lines, freeze a fifth of them as holdout, and wire
194
+ `eval/check.sh` into your nightly rebuild. That regression gate is what keeps
195
+ retrieval quality from silently rotting as the corpus grows.
196
+
197
+ ## How it compares
198
+
199
+ No cross-tool benchmark exists yet (see [Methodology & honest
200
+ limitations](BENCHMARK.md#methodology--honest-limitations) — we'd genuinely
201
+ like to see one run). Qualitative trade-offs, no fabricated numbers:
202
+
203
+ | Option | When to pick shelfmark instead | Why |
204
+ |---|---|---|
205
+ | **mem0** (managed, cloud-first memory layer) | You want full local data ownership and cross-repo search | One SQLite file, zero setup, MCP native. mem0 adds a hosted service you may not need |
206
+ | **Letta / MemGPT** (stateful agent framework) | You want a retriever, not a framework | Standalone tool that plugs into any MCP client; Letta expects you to adopt its agent runtime |
207
+ | **Zep** (hosted conversation memory) | You want permanent, local, cross-repo recall, not just chat threads | Single machine, no hosted dependency; Zep targets conversation history, not code/docs |
208
+ | **Cursor / Continue / Cody built-in indexing** | You want search outside one editor, or from a non-IDE agent | Runs anywhere MCP runs; editor-built-in indexes don't leave the editor |
209
+ | **DIY LangChain + Chroma/Weaviate** | You want hybrid retrieval and an eval gate without wiring it yourself | Reranking, RRF fusion, and `eval/check.sh` regression gates ship in the box |
210
+ | **Claude Code's built-in project memory** | You want hybrid (lexical + semantic) search across repos, not one workspace | File-based single-workspace memory has no ranking and no cross-repo scope |
211
+ | **Chroma / Weaviate raw, or Pinecone** (no framework) | You want zero infrastructure to stand up | One SQLite file vs. a vector DB service + embedding pipeline + glue code |
212
+ | **grep / ripgrep** | You need paraphrase recall, not just exact substrings | Lexical-only; shelfmark fuses BM25 with embeddings so "retry timeout" also matches "backoff on failure" |
213
+
214
+ Pick a hosted vector DB when you need multi-tenant scale across millions of
215
+ documents — that's a different problem than agent recall over your own repos.
216
+
217
+ Want to measure and improve retrieval ranking quality on your own pipeline,
218
+ independent of any specific agent? [hitgate](https://github.com/LucasSantana-Dev/hitgate)
219
+ provides label-free regression testing for hybrid retrievers. shelfmark and
220
+ hitgate share a common hybrid-retrieval foundation (BM25 + embeddings + RRF)
221
+ but serve complementary use cases: shelfmark for zero-setup agent memory with
222
+ MCP integration, hitgate for ranking evaluation and quality gates on any
223
+ retriever you already have.
224
+
225
+ ## Configuration
226
+
227
+ All optional — see `.env.example` for the full list. Highlights:
228
+
229
+ | var | default | effect |
230
+ |-----|---------|--------|
231
+ | `RAG_HOME` | `~/.shelfmark` | data dir (index, sources.yaml) |
232
+ | `RAG_MODEL` / `RAG_DIM` | e5-small / 384 | embedding model |
233
+ | `RAG_BM25_WEIGHT` | 1.5 | >1 favors lexical match |
234
+ | `RAG_RERANK_AUTO` | on | rerank weak/ambiguous queries |
235
+ | `RAG_CODE_RERANK` | off | bge-reranker-v2-m3 for code scopes (+4.9pp, ~2.2GB) |
236
+ | `RAG_QLOG` | off | local query telemetry (powers `report.py`) |
237
+
238
+ ## Contributing
239
+
240
+ Issues and PRs welcome — especially a real cross-tool benchmark (see [How it
241
+ compares](#how-it-compares)), support for more embedding models, or
242
+ non-Claude MCP client examples. If shelfmark saves your agent a guess, a star
243
+ helps others find it.
244
+
245
+ ## License
246
+
247
+ MIT
@@ -0,0 +1,197 @@
1
+ # shelfmark
2
+
3
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
4
+ [![GitHub stars](https://img.shields.io/github/stars/LucasSantana-Dev/shelfmark?style=flat)](https://github.com/LucasSantana-Dev/shelfmark/stargazers)
5
+ [![MCP](https://img.shields.io/badge/MCP-server-6b5ce7)](https://modelcontextprotocol.io)
6
+
7
+ ![shelfmark: local hybrid retrieval for agent memory and codebases](.github/shelfmark-card.png)
8
+
9
+ Local hybrid retrieval for agent memory and codebases. One SQLite file, no
10
+ services, no cloud. BM25 + dense embeddings fused with Reciprocal Rank Fusion,
11
+ an optional cross-encoder reranker, and an MCP server so coding agents
12
+ (Claude Code, Codex, anything MCP) can recall your notes, decisions, docs, and
13
+ code instead of guessing.
14
+
15
+ A shelfmark is the code a librarian writes on a book so it can be found again.
16
+ That is the whole product: before your agent answers, the librarian fetches the
17
+ handful of notes and code chunks most likely to matter and puts them on the
18
+ desk.
19
+
20
+ **[Why this exists](#why-this-exists)** · **[Quickstart](#quickstart)** ·
21
+ **[MCP server](#mcp-server-agent-integration)** ·
22
+ **[What gets indexed](#what-gets-indexed)** · **[Evaluation](#evaluation)** ·
23
+ **[How it compares](#how-it-compares)** · **[Configuration](#configuration)**
24
+
25
+ ## Why this exists
26
+
27
+ Agent harnesses accumulate knowledge: memory notes, ADRs, plans, standards,
28
+ handoffs, and the code itself. The useful answer to most questions is already
29
+ written down somewhere. shelfmark indexes all of it into one local SQLite file
30
+ and answers "what did we decide about X / where did we handle Y" in a single
31
+ query, with `path:line` citations.
32
+
33
+ shelfmark is the retrieval engine that came out of a year of running AI coding
34
+ agents daily — most recently distilled from
35
+ [forgekit](https://github.com/LucasSantana-Dev/forgekit), an AI dev toolkit for
36
+ coding agents. Every design choice below was forced by a real failure mode in
37
+ that daily use, not picked off a paper.
38
+
39
+ Design choices that fell out of a year of measured iteration (see
40
+ `eval/holdout-policy.md` and inline rationale comments):
41
+
42
+ - **Hybrid by default.** BM25 catches identifiers and exact terms; embeddings
43
+ catch paraphrase. RRF fusion beats either alone on mixed corpora.
44
+ - **Code-aware tokenization.** camelCase/snake_case sub-tokens on both corpus
45
+ and query sides ("create player" matches `createPlayer`). Measured +2.8pp
46
+ code / +3.2pp overall.
47
+ - **Symbol-definition boost.** Chunks whose defined symbol matches a query
48
+ identifier get a rank-0 signal (+2.8pp code, zero regressions).
49
+ - **Selective reranking.** Cross-encoder rerank helps code and standards,
50
+ *hurts* memory recall (measured -10.5pp). The rerank policy is scope-aware;
51
+ memory is never reranked.
52
+ - **Contextual chunk prefixes.** Every chunk embeds with a
53
+ `type | repo | file | symbol` header, not raw text.
54
+ - **Freshness without wall-clock.** Optional recency prior for memory scope,
55
+ deterministic (reference = max mtime among candidates), so evals stay
56
+ reproducible.
57
+
58
+ ## Quickstart
59
+
60
+ ```bash
61
+ pip install shelfmark-rag # or: pipx install shelfmark-rag
62
+
63
+ shelfmark-build # first run writes a starter ~/.shelfmark/sources.yaml — edit it, then rerun
64
+ shelfmark-query "how do we handle retry timeouts"
65
+ ```
66
+
67
+ First build downloads `intfloat/multilingual-e5-small` (~120MB). Everything
68
+ after that runs offline.
69
+
70
+ <details>
71
+ <summary>Prefer a local checkout instead? (contributing, editing the source)</summary>
72
+
73
+ ```bash
74
+ git clone https://github.com/LucasSantana-Dev/shelfmark && cd shelfmark
75
+ python3 -m venv venv && venv/bin/pip install -e .
76
+
77
+ venv/bin/shelfmark-build
78
+ venv/bin/shelfmark-query "how do we handle retry timeouts"
79
+ ```
80
+
81
+ </details>
82
+
83
+ ## MCP server (agent integration)
84
+
85
+ ```jsonc
86
+ // e.g. Claude Code: .mcp.json or ~/.claude.json
87
+ {
88
+ "mcpServers": {
89
+ "shelfmark": {
90
+ "command": "shelfmark-mcp"
91
+ }
92
+ }
93
+ }
94
+ ```
95
+
96
+ (Local checkout instead of `pipx install`? Use `"command": "/path/to/shelfmark/venv/bin/shelfmark-mcp"`.)
97
+
98
+ Two tools:
99
+
100
+ - `rag_query` — full-corpus hybrid search (code, docs, commits, notes).
101
+ Auto-scopes to the repo your agent is working in.
102
+ - `search_knowledge` — cross-project search over durable knowledge only
103
+ (memory/standards/plans/handoffs/adrs; configurable via
104
+ `RAG_KNOWLEDGE_SCOPE`). Never reranked, by measurement.
105
+
106
+ `examples/claude-code/` has the full loop: auto-recall on every prompt
107
+ (UserPromptSubmit), incremental reindex on file writes (PostToolUse), drift
108
+ reindex + weekly report at session start, and a nightly rebuild with an eval
109
+ regression gate.
110
+
111
+ ## What gets indexed
112
+
113
+ `sources.yaml` declares everything (see `sources.yaml.example`):
114
+
115
+ | kind | what |
116
+ |------|------|
117
+ | `repos` | source code (py/ts/js/sh, symbol-aware chunking), `docs/**`, README, CHANGELOG, `docs/specs/**`, roadmap, last 180d of commit messages |
118
+ | `sources` | arbitrary markdown globs, each under a free `type` label you filter on at query time |
119
+ | `code_globs` | loose scripts outside any repo |
120
+
121
+ Incremental reindex (`indexer.py --incremental <files>`) keeps writes cheap;
122
+ `session_chunker.py` can additionally index agent session transcripts.
123
+
124
+ ## Evaluation
125
+
126
+ The eval harness is the part most RAG setups skip. `eval/run.py` scores
127
+ Hit@1/3/5 + MRR per scope against a JSONL dataset; `eval/check.sh` gates any
128
+ change at >5pp regression vs a frozen baseline; `eval/holdout-policy.md`
129
+ documents the train/holdout discipline (the holdout set is never used for
130
+ tuning — numbers quoted from it are honest).
131
+
132
+ This repo ships a public, reproducible dataset (`eval/dataset-public.jsonl`)
133
+ whose queries target this repository's own code and docs:
134
+
135
+ ```bash
136
+ venv/bin/python indexer.py # index this repo (sources.yaml.example works as-is)
137
+ venv/bin/python eval/run.py --dataset eval/dataset-public.jsonl --label mine
138
+ ```
139
+
140
+ Benchmark results and methodology: [BENCHMARK.md](BENCHMARK.md).
141
+
142
+ To evaluate on YOUR corpus, write ~50 `{"query", "expect_path_contains",
143
+ "expect_scope"}` lines, freeze a fifth of them as holdout, and wire
144
+ `eval/check.sh` into your nightly rebuild. That regression gate is what keeps
145
+ retrieval quality from silently rotting as the corpus grows.
146
+
147
+ ## How it compares
148
+
149
+ No cross-tool benchmark exists yet (see [Methodology & honest
150
+ limitations](BENCHMARK.md#methodology--honest-limitations) — we'd genuinely
151
+ like to see one run). Qualitative trade-offs, no fabricated numbers:
152
+
153
+ | Option | When to pick shelfmark instead | Why |
154
+ |---|---|---|
155
+ | **mem0** (managed, cloud-first memory layer) | You want full local data ownership and cross-repo search | One SQLite file, zero setup, MCP native. mem0 adds a hosted service you may not need |
156
+ | **Letta / MemGPT** (stateful agent framework) | You want a retriever, not a framework | Standalone tool that plugs into any MCP client; Letta expects you to adopt its agent runtime |
157
+ | **Zep** (hosted conversation memory) | You want permanent, local, cross-repo recall, not just chat threads | Single machine, no hosted dependency; Zep targets conversation history, not code/docs |
158
+ | **Cursor / Continue / Cody built-in indexing** | You want search outside one editor, or from a non-IDE agent | Runs anywhere MCP runs; editor-built-in indexes don't leave the editor |
159
+ | **DIY LangChain + Chroma/Weaviate** | You want hybrid retrieval and an eval gate without wiring it yourself | Reranking, RRF fusion, and `eval/check.sh` regression gates ship in the box |
160
+ | **Claude Code's built-in project memory** | You want hybrid (lexical + semantic) search across repos, not one workspace | File-based single-workspace memory has no ranking and no cross-repo scope |
161
+ | **Chroma / Weaviate raw, or Pinecone** (no framework) | You want zero infrastructure to stand up | One SQLite file vs. a vector DB service + embedding pipeline + glue code |
162
+ | **grep / ripgrep** | You need paraphrase recall, not just exact substrings | Lexical-only; shelfmark fuses BM25 with embeddings so "retry timeout" also matches "backoff on failure" |
163
+
164
+ Pick a hosted vector DB when you need multi-tenant scale across millions of
165
+ documents — that's a different problem than agent recall over your own repos.
166
+
167
+ Want to measure and improve retrieval ranking quality on your own pipeline,
168
+ independent of any specific agent? [hitgate](https://github.com/LucasSantana-Dev/hitgate)
169
+ provides label-free regression testing for hybrid retrievers. shelfmark and
170
+ hitgate share a common hybrid-retrieval foundation (BM25 + embeddings + RRF)
171
+ but serve complementary use cases: shelfmark for zero-setup agent memory with
172
+ MCP integration, hitgate for ranking evaluation and quality gates on any
173
+ retriever you already have.
174
+
175
+ ## Configuration
176
+
177
+ All optional — see `.env.example` for the full list. Highlights:
178
+
179
+ | var | default | effect |
180
+ |-----|---------|--------|
181
+ | `RAG_HOME` | `~/.shelfmark` | data dir (index, sources.yaml) |
182
+ | `RAG_MODEL` / `RAG_DIM` | e5-small / 384 | embedding model |
183
+ | `RAG_BM25_WEIGHT` | 1.5 | >1 favors lexical match |
184
+ | `RAG_RERANK_AUTO` | on | rerank weak/ambiguous queries |
185
+ | `RAG_CODE_RERANK` | off | bge-reranker-v2-m3 for code scopes (+4.9pp, ~2.2GB) |
186
+ | `RAG_QLOG` | off | local query telemetry (powers `report.py`) |
187
+
188
+ ## Contributing
189
+
190
+ Issues and PRs welcome — especially a real cross-tool benchmark (see [How it
191
+ compares](#how-it-compares)), support for more embedding models, or
192
+ non-Claude MCP client examples. If shelfmark saves your agent a guess, a star
193
+ helps others find it.
194
+
195
+ ## License
196
+
197
+ MIT
@@ -0,0 +1,155 @@
1
+ """Language-aware chunkers. Each returns list[(start_line, end_line, text, symbol_name)].
2
+
3
+ Keep chunks:
4
+ - Python: one chunk per top-level def/class (via stdlib ast).
5
+ - TS/JS: regex on top-level `export? (async )?(function|class|const NAME =)` blocks, brace-matched.
6
+ - Shell: regex on `NAME() {` blocks through closing `^}`.
7
+ - Config / others: fall back to markdown-style word-count windows.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import re
13
+ from pathlib import Path
14
+ from typing import List, Tuple
15
+
16
+ Chunk = Tuple[int, int, str, str] # start_line (1-idx), end_line, text, symbol
17
+
18
+ MAX_CHUNK_LINES = 250
19
+ MIN_CHUNK_CHARS = 40
20
+
21
+
22
+ def chunk_python(text: str) -> List[Chunk]:
23
+ lines = text.splitlines()
24
+ try:
25
+ tree = ast.parse(text)
26
+ except SyntaxError:
27
+ return chunk_fallback(text)
28
+ chunks: List[Chunk] = []
29
+ for node in tree.body:
30
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
31
+ start = getattr(node, "lineno", 1)
32
+ end = getattr(node, "end_lineno", start)
33
+ body = "\n".join(lines[start - 1 : end])
34
+ if len(body) >= MIN_CHUNK_CHARS:
35
+ chunks.append((start, end, body[:8000], node.name))
36
+ if not chunks:
37
+ return chunk_fallback(text)
38
+ return chunks
39
+
40
+
41
+ _TS_DECL = re.compile(
42
+ r"^(?P<indent>[ \t]*)"
43
+ r"(?:export\s+(?:default\s+)?)?"
44
+ r"(?:async\s+)?"
45
+ r"(?:function\*?\s+(?P<fn>[A-Za-z_$][\w$]*)"
46
+ r"|class\s+(?P<cls>[A-Za-z_$][\w$]*)"
47
+ r"|(?:const|let|var)\s+(?P<var>[A-Za-z_$][\w$]*)\s*[:=]"
48
+ r"|(?:interface|type|enum)\s+(?P<ty>[A-Za-z_$][\w$]*))",
49
+ re.MULTILINE,
50
+ )
51
+
52
+
53
+ def chunk_ts(text: str) -> List[Chunk]:
54
+ lines = text.splitlines()
55
+ matches = list(_TS_DECL.finditer(text))
56
+ if not matches:
57
+ return chunk_fallback(text)
58
+ chunks: List[Chunk] = []
59
+ for i, m in enumerate(matches):
60
+ if m.group("indent"):
61
+ continue # only top-level declarations
62
+ name = m.group("fn") or m.group("cls") or m.group("var") or m.group("ty") or "?"
63
+ start_line = text.count("\n", 0, m.start()) + 1
64
+ end_line = (
65
+ text.count("\n", 0, matches[i + 1].start()) + 1
66
+ if i + 1 < len(matches)
67
+ else len(lines) + 1
68
+ )
69
+ end_line = min(end_line, start_line + MAX_CHUNK_LINES)
70
+ body = "\n".join(lines[start_line - 1 : end_line - 1])
71
+ if len(body) >= MIN_CHUNK_CHARS:
72
+ chunks.append((start_line, end_line - 1, body[:8000], name))
73
+ return chunks or chunk_fallback(text)
74
+
75
+
76
+ _SHELL_FN = re.compile(r"^(?P<name>[A-Za-z_][\w]*)\s*\(\)\s*\{", re.MULTILINE)
77
+
78
+
79
+ def chunk_shell(text: str) -> List[Chunk]:
80
+ lines = text.splitlines()
81
+ matches = list(_SHELL_FN.finditer(text))
82
+ if not matches:
83
+ return chunk_fallback(text)
84
+ chunks: List[Chunk] = []
85
+ for m in matches:
86
+ name = m.group("name")
87
+ start = text.count("\n", 0, m.start()) + 1
88
+ depth = 0
89
+ i = start - 1
90
+ end = start
91
+ while i < len(lines):
92
+ depth += lines[i].count("{") - lines[i].count("}")
93
+ i += 1
94
+ if depth <= 0 and i > start - 1:
95
+ end = i
96
+ break
97
+ body = "\n".join(lines[start - 1 : end])
98
+ if len(body) >= MIN_CHUNK_CHARS:
99
+ chunks.append((start, end, body[:8000], name))
100
+ return chunks or chunk_fallback(text)
101
+
102
+
103
+ def chunk_fallback(text: str) -> List[Chunk]:
104
+ """Word-count window for non-code / unrecognized content."""
105
+ lines = text.splitlines()
106
+ if not lines:
107
+ return []
108
+ chunks: List[Chunk] = []
109
+ i = 0
110
+ while i < len(lines):
111
+ start = i
112
+ word_count = 0
113
+ while i < len(lines) and word_count < 300:
114
+ word_count += len(lines[i].split())
115
+ i += 1
116
+ body = "\n".join(lines[start:i]).strip()
117
+ if body and len(body) >= MIN_CHUNK_CHARS:
118
+ chunks.append((start + 1, i, body[:8000], ""))
119
+ # overlap
120
+ if i >= len(lines):
121
+ break
122
+ i = max(start + 1, i - 6)
123
+ return chunks
124
+
125
+
126
+ def detect_language(path: Path) -> str:
127
+ suf = path.suffix.lower()
128
+ return {
129
+ ".py": "python",
130
+ ".ts": "typescript",
131
+ ".tsx": "typescript",
132
+ ".js": "javascript",
133
+ ".jsx": "javascript",
134
+ ".mjs": "javascript",
135
+ ".sh": "shell",
136
+ ".bash": "shell",
137
+ ".zsh": "shell",
138
+ ".md": "markdown",
139
+ ".yml": "yaml",
140
+ ".yaml": "yaml",
141
+ ".json": "json",
142
+ ".toml": "toml",
143
+ ".rules": "text",
144
+ }.get(suf, "text")
145
+
146
+
147
+ def chunk_file(path: Path, text: str) -> List[Chunk]:
148
+ lang = detect_language(path)
149
+ if lang == "python":
150
+ return chunk_python(text)
151
+ if lang in ("typescript", "javascript"):
152
+ return chunk_ts(text)
153
+ if lang == "shell":
154
+ return chunk_shell(text)
155
+ return chunk_fallback(text)