akasha
Officialby Sifr-Dev
README.md
# Akasha
**Deterministic, citation-grounded retrieval over local Markdown and text, with a hybrid BM25 + hashed-dense ranker, extractive answers, and a stdio MCP server.**
[](https://github.com/Sifr-Dev/Akasha/actions/workflows/ci.yml)
[](https://www.python.org/)
[](LICENSE)
## What it is
Akasha is a retrieval kernel for question answering over a small, trusted corpus. It indexes documents into offset-exact chunks, ranks them with Okapi BM25 and a deterministic hashed-dense retriever, fuses the two rankings with reciprocal rank fusion, and returns a verbatim source span with exact citations.
It is not a chat system or an agent framework. Answers are extracted, never generated: if the evidence coverage is too low, Akasha refuses with a machine-readable reason instead of writing plausible prose. There are no model calls, API keys, or network requests at query time, and the runtime has no dependencies outside the Python standard library.
The project's differentiators are structural rather than aspirational:
- **Reproducible:** stable chunk ids, sorted-term scoring, content-derived tie-breaks, and a byte-for-byte determinism check in the evaluation harness.
- **Fail-closed:** refusal is a first-class outcome with an auditable reason code.
- **Auditable citations:** every citation is re-read from the stored document and compared character for character before an answer is returned.
- **Tested protocol:** the MCP surface is exercised in-process and over a real subprocess stdio round trip, without an SDK.
## Current capabilities
- **Corpus ingest and chunking.** Markdown, `.markdown`, and plain text; simple front matter; paragraph/word-boundary-aware character windows with configurable overlap; stable chunk ids of the form `<doc_id>:<ordinal>:<start>-<end>`; exact half-open offsets. Implemented in `src/akasha/corpus.py`, covered by `tests/test_corpus.py`.
- **BM25.** A direct Okapi implementation with configurable `k1`/`b`, positive Lucene IDF, Porter stemming, stopword removal, deduplicated query terms, and sorted-term accumulation. Implemented in `src/akasha/bm25.py`, covered by `tests/test_bm25.py`.
- **Dense retrieval.** Signed BLAKE2b feature hashing into 2048 dimensions over word unigrams, word bigrams, and character 3–5-grams; L2-normalized sparse cosine. No pretrained model. Implemented in `src/akasha/dense.py`, covered by `tests/test_dense.py`.
- **Hybrid fusion.** Reciprocal Rank Fusion with `k=60`, deduplication, optional weights, and chunk-id tie-breaks. Implemented in `src/akasha/fusion.py`, covered by `tests/test_fusion.py`.
- **Metadata filters.** Source path or glob, all-tags matching, inclusive date ranges; filters compose with AND and can be combined with any retrieval mode. Implemented in `src/akasha/store.py`, covered by `tests/test_store.py`.
- **Extractive answers.** Sentence/list-item candidates scored by IDF-weighted query coverage; at most two adjacent sentences of the same chunk; support score in `[0, 1]`; default threshold `0.5`. Implemented in `src/akasha/answer.py`, covered by `tests/test_answer.py`.
- **Citation integrity.** A citation carries doc id, chunk id, source, title, character range, and exact quote. The answer is refused if the quote does not match both the stored document and the cited chunk. Covered by `tests/test_answer.py`.
- **MCP server.** Stdio, newline-delimited JSON-RPC 2.0 with `initialize`, `tools/list`, `tools/call`, and `ping`; tools `akasha_search`, `akasha_read`, and `akasha_answer`; standard JSON-RPC error codes and `isError` tool results. Implemented in `src/akasha/mcp.py`, covered by `tests/test_mcp.py` including a subprocess session.
- **Evaluation harness.** A 26-question golden set over the included corpus (20 answerable, 6 unanswerable), recall@1/3/5/10, MRR, citation precision/recall, refusal accuracy, p50/p95 latency, and BM25/dense/hybrid ablations. Implemented in `src/akasha/eval.py`, covered by `tests/test_eval.py`.
- **CLI and persistence.** `index`, `search`, `ask`, `eval`, and `mcp` commands; a versioned JSON index written atomically. Implemented in `src/akasha/cli.py` and `src/akasha/store.py`, covered by `tests/test_cli.py`.
## Quick start
Requires Python 3.12+ and [uv](https://docs.astral.sh/uv/).
```console
$ uv sync --frozen
$ uv run akasha index --corpus corpus
indexed 14 documents / 38 chunks / 16765 chars -> .akasha/index.json
$ uv run akasha search "reciprocal rank fusion" -k 3
$ uv run akasha ask "What is the reciprocal rank fusion constant k?"
ANSWER (support 1.000 ≥ 0.500)
The reciprocal rank fusion constant k is 60 by default.
CITATION docs/fusion.md [118:173] doc=docs-fusion chunk=docs-fusion:0000:000001-000619
```
Refusal is a normal outcome and has its own exit code when requested:
```console
$ uv run akasha ask "How do I configure Akasha to use OpenAI embeddings?"
REFUSED (below_support_threshold) support=0.213
$ uv run akasha ask "How do I configure Akasha to use OpenAI embeddings?" --fail-on-refusal
$ echo $?
3
```
Run the offline evaluation and write `eval/results.json`:
```console
$ uv run akasha eval
```
Start the MCP server on stdin/stdout:
```console
$ uv run akasha mcp --index .akasha/index.json
```
A complete initialize exchange, copied from a real run:
```console
$ printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \
| uv run akasha mcp --index .akasha/index.json
{"id": 1, "jsonrpc": "2.0", "result": {"capabilities": {"tools": {"listChanged": false}}, "protocolVersion": "2024-11-05", "serverInfo": {"name": "akasha", "version": "0.1.0"}}}
```
The three MCP tools accept JSON arguments:
| Tool | Arguments |
|---|---|
| `akasha_search` | `query`, optional `top_k`, `mode`, `filters` |
| `akasha_read` | exactly one of `chunk_id` or `doc_id`, plus optional `start`, `end`, `max_chars` |
| `akasha_answer` | `query`, optional `top_k`, `threshold`, `mode`, `filters` |
Example tool call and response shape:
```json
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"akasha_search","arguments":{"query":"RRF constant","top_k":1}}}
```
```json
{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"{...}"}],"structuredContent":{"query":"RRF constant","mode":"hybrid","count":1,"results":[...]},"isError":false}}
```
`filters` accepts `source`, `tags`, `date_from`, and `date_to`. Source supports exact relative paths and shell globs; tags require every listed tag; dates are inclusive `YYYY-MM-DD` and exclude undated documents.
## Verification
Run on this machine (AMD Ryzen 7 7435HS, 16 threads, Linux 7.3.4, Python 3.12.16) on 2026-11-28:
```console
$ uv run ruff check src tests
All checks passed!
$ uv run ruff format --check src tests
24 files already formatted
$ uv run pytest -q
175 passed in 5.86s
$ uv run akasha eval
variant R@1 R@3 R@5 R@10 MRR cit-P cit-R refusal p50ms p95ms
-------- ------ ------ ------ ------ ------ ------ ------ ------- ------ ------
bm25 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 8.34 9.12
dense 0.900 1.000 1.000 1.000 0.950 1.000 1.000 1.000 8.57 9.44
hybrid 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 8.52 9.55
golden: 26 questions (20 answerable, 6 unanswerable); results -> eval/results.json
```
The hybrid determinism check re-ran all 26 questions and reported `26/26` byte-identical serialized answer objects.
The 175 tests include 38 canonical Porter stemmer cases. The integration tests build the real 14-document corpus, run the real MCP subprocess, and execute the full evaluation harness; there are no mocks around retrieval or protocol framing.
### Benchmark methodology
- **Hardware:** AMD Ryzen 7 7435HS, 16 logical CPUs, 15 GiB RAM, Linux 7.3.4-zen2, Python 3.12.16, single process, no GPU.
- **Corpus:** 14 Markdown documents, 38 chunks, 16,765 characters. Default chunk window 640 characters, overlap 120.
- **Questions:** 26 total: 20 answerable with 20 verbatim gold evidence spans, and 6 unanswerable near-domain questions. The golden set is `eval/golden.jsonl`.
- **Retrieval metrics:** document-level recall@k and MRR over the 20 answerable questions, using the top 10 chunks from each variant.
- **Answer metrics:** the answer pipeline uses top 5 chunks; citation precision is the fraction of produced citations overlapping a gold span, and citation recall is the fraction of gold spans covered by a citation.
- **Refusal accuracy:** over all 26 questions. A gold-refusal is an unanswerable question; a predicted refusal is an empty answer with a reason code.
- **Latency:** wall-clock time per question for retrieval plus answer assembly, measured after one untimed warm-up pass per variant, over 26 timed samples per variant. p50/p95 use the nearest-rank percentile. `eval/results.json` records the environment and configuration for every run.
- **Ablations:** the same pipeline with `mode=bm25`, `mode=dense`, and `mode=hybrid`; chunking, threshold, and corpus are held constant.
- **Determinism:** the hybrid variant is run a second time for every question and the complete serialized answer object is compared.
### Reading the numbers
The scores are saturated on this set: both retrievers already find the correct document in the top five, and the questions use vocabulary that appears in the gold sentence. That makes the table a regression baseline, not evidence of open-domain superiority. The meaningful differences are structural: exact citation verification, refusal reason codes, byte-identical reruns, and a protocol-level MCP test suite. Dense-only retrieval drops one first-place result (`R@1 0.900`) while hybrid recovers it, which is the expected effect of fusion on this corpus.
## Architecture
```
src/akasha/
corpus.py front matter, document ids, chunker, corpus loading
text.py ASCII tokenizer, stopwords, vendored Porter stemmer, stem matching
bm25.py BM25 index, scoring, serialization
dense.py signed feature hashing, cosine index, serialization
fusion.py reciprocal rank fusion
store.py index build/load/save, filters, search, read operations
answer.py sentence spans, support scoring, citations, fail-closed refusal
mcp.py JSON-RPC 2.0 stdio server and tool schemas
eval.py golden loading, metrics, ablations, latency, determinism
cli.py argument parsing and human/JSON output
types.py immutable payload dataclasses
```
Request path: `load_corpus` → `chunk_corpus` → `BM25Index` + `DenseIndex` → `reciprocal_rank_fusion` → `answer_question` → verified `Citation`.
Index artifact: a single JSON file (`akasha.index.v1`) containing document bodies, chunk ranges, BM25 term frequencies and IDF, and dense vectors. It is written through a temporary file and `os.replace`, so a crashed write does not leave a partial index. The index contains full corpus text and should be protected like the corpus itself.
Determinism rules:
- chunk ids are derived from source path, ordinal, and character offsets;
- BM25 accumulates in sorted term order and breaks ties on chunk id;
- dense features are sorted before hashing and BLAKE2b is fixed;
- RRF breaks ties on chunk id;
- answer selection breaks ties on source position and chunk id;
- no randomness, wall-clock time, locale, hash seed, or network input enters a ranking or an answer.
## Limitations
- **Hashed dense retrieval is not semantic.** It matches vocabulary, subwords, and bigrams; it cannot equate “car” and “automobile”. Hash collisions add noise and fixed 2048 dimensions will saturate on larger corpora.
- **The answer is extractive.** At most two adjacent sentences from one chunk. It cannot synthesize across documents, perform arithmetic, or resolve pronouns. Multi-hop questions are refused.
- **Support is a heuristic.** It is IDF-weighted query-term coverage, not a probability or a calibrated model confidence. The threshold is a fixed global `0.5` and is not tuned per corpus.
- **The golden set is small and self-authored.** Corpus and questions were written together. The observed 1.000 scores should be read as a regression baseline; they say nothing about open-domain QA.
- **Chunking is character-based.** Windows prefer paragraph and word boundaries but can still split code blocks, tables, or very long sentences.
- **English-specific analysis.** The Porter stemmer and the ASCII token pattern are English-oriented. Non-English text will tokenize partially and retrieve poorly.
- **Latency is tiny-corpus latency.** These numbers describe a 38-chunk in-memory index on one laptop, not a network service or a million-document corpus.
- **Full rebuild only.** There is no incremental indexing or deletion. Re-run `akasha index` after corpus changes.
- **Protocol scope is small.** The MCP server implements the three tools and the lifecycle methods needed for a local client. It does not implement resources, prompts, sampling, subscriptions, or HTTP transport.
- **No authentication.** The server is for local stdio clients that already have file access. There is no network transport, authorization model, or multi-tenant isolation.
## Roadmap (NOT IMPLEMENTED)
Nothing below exists today; it is future work, not a claimed feature.
- Incremental index updates and document deletion with stable id invalidation.
- A neural or learned sparse retriever behind the same deterministic interfaces.
- A cross-encoder reranker with a separate, opt-in evaluation track.
- Multi-document extractive synthesis with per-sentence citations.
- Multilingual tokenization and stemming.
- HTTP/SSE MCP transport with authentication and authorization.
- Larger and independently authored evaluation sets, including adversarial and paraphrase splits.
- Query-time determinism verification in CI against a committed golden ranking hash.
## License
MIT. See [LICENSE](LICENSE).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues