Metadata-Version: 2.5
Name: budgetdex
Version: 0.0.1
Summary: Local, LLM-free index over personal documents that returns search results packed into a token budget.
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: bm25,japanese,local-first,mcp,notion,postgres,rag,search,sqlite,token-budget
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Natural Language :: English
Classifier: Natural Language :: Japanese
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Text Processing :: Indexing
Requires-Python: >=3.11
Requires-Dist: mcp<3,>=2.3.0
Provides-Extra: docx
Requires-Dist: python-docx>=1.1; extra == 'docx'
Provides-Extra: pdf
Requires-Dist: pypdf>=5; extra == 'pdf'
Provides-Extra: postgres
Requires-Dist: psycopg[binary]>=3.2; extra == 'postgres'
Provides-Extra: vec
Requires-Dist: numpy>=2.4.6; extra == 'vec'
Requires-Dist: onnxruntime>=1.32.0; extra == 'vec'
Requires-Dist: tokenizers>=0.23.3; extra == 'vec'
Provides-Extra: xlsx
Requires-Dist: openpyxl>=3.1; extra == 'xlsx'
Description-Content-Type: text/markdown

# budgetdex

A local index over your own documents and tables, for AI agents.
The agent says how many tokens it can spend; budgetdex returns the most useful hits packed into that budget (top hits in full, the rest as snippets or title lines).
No LLM is called to build or query the index, no account is needed, and nothing leaves your machine unless you add a connector or download the optional model.

Status: **alpha (0.0.1)**. Tested on macOS (Apple silicon). Linux runs in CI; Windows is not tested.
Search headers and CLI messages are currently in **Japanese** (the tool works on English and Japanese text alike).
日本語の説明は [README_JA.md](README_JA.md)。

## Install

```bash
uv tool install "budgetdex[vec]"      # or: pipx install "budgetdex[vec]"
```

Extras: `vec` (vector search: numpy, onnxruntime, tokenizers; no PyTorch), `xlsx` (openpyxl), `pdf` (pypdf), `docx` (python-docx), `postgres` (psycopg). Combine them as `budgetdex[vec,xlsx,pdf,docx]`. The core depends only on `mcp`. Without an extra, the affected files are listed by `budgetdex status` with an install hint, and search uses BM25 alone. Python 3.11+.

## 60-second quickstart

```bash
budgetdex add ~/notes                     # index a folder (md, txt, csv, tsv; xlsx/pdf/docx with extras)
budgetdex search "refund deadline" -b 500 # results packed into 500 tokens
budgetdex get <id> -b 800                 # full text of one hit
budgetdex sql "select count(*) from my_table"   # read-only SQL over indexed CSV/xlsx tables
budgetdex status                          # what is indexed, what was skipped and why
```

Later runs of `budgetdex sync` re-read changed files only. The index lives in `~/.budgetdex/default.db` (set `BUDGETDEX_HOME` to move it).

Vectors are optional (better for paraphrases and English/Japanese mixes):

```bash
budgetdex embed --download    # one-time ~135 MB model download, then embeds all chunks
```

After later CLI syncs, run `budgetdex embed` again for new chunks; the MCP server does this by itself in the background.

## Connect an agent (MCP over stdio)

Claude Code:

```bash
claude mcp add budgetdex -- budgetdex mcp
```

Any other MCP client (JSON config):

```json
{
  "mcpServers": {
    "budgetdex": { "command": "budgetdex", "args": ["mcp"] }
  }
}
```

The server re-syncs all sources in the background when it starts. A Claude Code plugin (server definition plus a usage skill) is in `plugin/`.

| Tool | What it does |
|---|---|
| `search(query, budget, where)` | Ranked hits within `budget` tokens, one `[id] title｜source date` line each. `where` narrows to a path glob. Items already returned in the session come back as a title line marked `※既出`. A header ending in `一致弱め` means the matches are weak (the answer may not be in the index). |
| `get(id, budget, start)` | Full text of one hit within `budget`; a cut text ends with the `start` to continue from. |
| `sql(query, budget)` | Read-only SQL over the tables that search shows as `表` (CSV/TSV, xlsx, Notion databases, Postgres). Tab-separated, within `budget`. |

The same is available from Python: `budgetdex.open().search("...", budget=800)`.

## Profiles and resources

Chosen per index with `budgetdex profile NAME`.

| Profile | What it does | Memory (one CLI process) | Search p50 | Extra disk |
|---|---|---|---|---|
| `light` | BM25 only, no model | ~19–23 MB | ~35–45 ms | — |
| `standard` (default) | BM25 + vectors (multilingual-e5-small) | ~205 MB (peaks ~390–470 MB while loading / embedding) | ~50–70 ms | model ~143 MB |
| `max` | + cross-encoder re-ranking | ~466 MB | ~0.3 s | + ~144 MB |

Without the model, `standard` behaves like `light`-style BM25 search. As an MCP server, idle memory is ~51–54 MB (no model is loaded until a search needs it); after 100 searches ~61 MB (`light`) and ~240–260 MB (`standard`). The index file is about 3x the size of the indexed text.
Measured on one machine (Apple M2 Pro, a 1.5 MB / 1,525-chunk folder, macOS `phys_footprint`). Your numbers will differ.

## Connectors (opt-in)

Nothing is contacted unless you add it explicitly. Secrets come from an environment variable (`--env VAR`, default `BUDGETDEX_POSTGRES_URL` / `NOTION_TOKEN`) or, on macOS only, the keychain (`--keychain SERVICE`; on Linux/Windows `add --keychain` stops with an error, use `--env`). Secrets are read when needed and never stored in the index, printed or returned to the agent.

**Postgres / Supabase** — `budgetdex add postgres [--schema NAME]` (extra `postgres`).
- At sync, only the schema and planner statistics are read (table and column names, types, comments, approximate counts). No rows are copied into the index.
- `sql` queries go to the database in a `READ ONLY` transaction with a statement timeout, a server-side cursor, a row cap and one 5 s deadline. A textual pre-check refuses writes first.
- Limits: these checks are a second line of defence. **Use a database role that can only `SELECT`** — a function with side effects can still run inside a read-only transaction. Joins between local tables and Postgres tables are refused. Tables with row-level security and no policy for your role return 0 rows (the card shows `RLS有効` and `budgetdex status` prints a policy example).
- Supabase: use the Session pooler connection string with a dedicated read-only role. Step-by-step guide (Japanese) in [README_JA.md](README_JA.md), section “Supabase：手順”.

**Notion API** — `budgetdex add notion`.
- Create an internal integration with only the "Read content" capability and share the pages you want indexed with it. The connector issues only `GET` requests and `POST /search` to `api.notion.com`.
- Limits: nested blocks up to 8 levels and at most 150 block requests per page; pages cut by a limit or with unreadable blocks are indexed partially and listed in `budgetdex status`. System properties (created by, etc.) are not indexed; people properties only by the display name the API already returns.

Notion "Markdown & CSV" export zips can also be added as files (`budgetdex add export.zip`), without any network access.

## Privacy and security

- **What leaves the machine:** nothing, except (1) the connectors you add (your Postgres host, `api.notion.com`), and (2) the explicit `budgetdex embed --download`. No telemetry.
- **The model download** fetches exactly two files per model from `https://huggingface.co/<repo>/resolve/<pinned revision>/<file>`, following Hugging Face's redirect to its file CDN (User-Agent `budgetdex`):
  - `Xenova/multilingual-e5-small` @ `761b726d…`: `onnx/model_quantized.onnx` (118,308,185 bytes) and `tokenizer.json` (17,082,730 bytes) — ~135 MB.
  - With `--reranker`: `cross-encoder/mmarco-mMiniLMv2-L12-H384-v1` @ `1427fd65…`: `onnx/model_qint8_arm64.onnx` (118,620,017 bytes, plain int8 ops, runs on any CPU) and `tokenizer.json` (17,082,660 bytes) — ~136 MB.
  - The announced size is checked before reading; size and sha256 are checked before a file is put in place and again when the model is loaded. An interrupted download leaves no partial file. Files go to `$BUDGETDEX_HOME/models/`.
- **The index is a plaintext copy** of what you indexed (`default.db`, mode 0600, not encrypted). Deleting a source file removes it at the next sync.
- **Ignored by default:** `.env*`, key files (`*.pem`, `id_rsa*`, ...), names that look like passwords / tokens / API keys, `.git`, `.ssh`, `.aws`, `.gnupg`, `.config`, `node_modules`, `.venv`, ... and `.gitignore`d paths. `--allow GLOB` overrides only `.gitignore`. Obvious secrets (PEM keys, known key prefixes, `password=...`) are masked in output.
- **Table rows are not in the search index.** Table cards show column names, types and counts, but no cell values unless you opt in per source (`--table-values`). Rows are reachable through `sql`. One exception: when a question word (3+ characters) appears in no document but as a whole word in a text cell of a local table, the search header names the table, column and row count (never the value); personal- and secret-looking columns are never read for this.
- **Local `sql`** runs on a separate read-only SQLite connection with an authorizer (SELECT on user tables only; no writes, ATTACH, PRAGMA or extensions), a 5 s timeout and a row cap.
- **Prompt injection cannot be fully prevented.** Results are returned as data with their source, but a document can still contain instructions an agent may follow. Index only what you would let the agent read.

See [SECURITY.md](SECURITY.md) to report a problem.

## Models and licences

No model is bundled; the optional ones are downloaded by you and keep their own licences:
- `intfloat/multilingual-e5-small` (ONNX build `Xenova/multilingual-e5-small`): MIT. <!-- TODO(owner): confirm on both model cards before release -->
- `cross-encoder/mmarco-mMiniLMv2-L12-H384-v1`: Apache-2.0 per its model card; it was trained on mMARCO, a translation of MS MARCO, whose terms restrict use to non-commercial research. Check whether that matters for your use before enabling `max`. <!-- TODO(owner): verify -->

`src/budgetdex/spm.py` re-implements the SentencePiece-Unigram segmentation of Hugging Face `tokenizers` (Apache-2.0) to save memory; see [NOTICE](NOTICE).

## Evaluation (honest version)

Measured at retrieval level: a question counts as answered when the answer string appears in the returned text. This is not an end-to-end agent measurement. **Token counts are this package's own estimate, not calibrated against a real tokenizer.**

- **Synthetic lab** (generated fictional Notion pages, Postgres tables and files; two unseen seeds, ~90 search questions each): profile `standard` at budget 1,000 answered **92% and 96%** using **~885 tokens** on average; returning the top 10 hits in full answered 93% and 96% using ~2,100–2,200 tokens. The data is synthetic and written by the same project, so real documents may behave differently.
- **Private set** (60 questions over a real personal folder, not used for tuning, scored once): plain hybrid top-10 RAG 0.73 at 3,802 tokens; `standard` 0.68–0.75 at budgets 1,000–1,900 (~880–1,690 tokens). Roughly the same answer rate at a quarter to a half of the tokens; the difference is within noise. An earlier independent 50-question set did *not* reach parity (0.52 vs 0.62).
- **Weak spots:** questions in another language than the document (e.g. English question, Japanese column names), paraphrases that share no words with the text, and detecting that the answer is not in the index at all.

## Limitations

- Alpha: the index format and output may change between 0.0.x versions.
- Output headers and messages are in Japanese.
- Cross-language and paraphrase questions are clearly weaker than same-language keyword questions (see above).
- Local table columns (CSV, TSV, xlsx, Notion databases) are stored as INTEGER or REAL in `sql` only when every non-empty cell is a clean number (no leading zeros, at most 15 digits, thousands separators like `1,234` allowed, decimals that a double keeps exactly); empty cells of those columns are NULL. Everything else stays text: codes with leading zeros (`007`, postal codes), longer digit strings, full-width digits, currency / units / percentages (`¥1,200`, `30%`), `(5)`, dates and mixed columns. The table card says 整数 / 数値 for numeric columns and 数字の文字列 for numeric-looking text, which compares as text (cast it yourself if you need numbers). Indexes from before this change are converted once when opened writable (`budgetdex status` shows tables still waiting).
- Token counts are estimates; leave some margin in a hard context limit.
- One index per `BUDGETDEX_HOME`; no multi-user or server mode.
- macOS keychain support only on macOS; Windows is untested.

## Uninstall

```bash
claude mcp remove budgetdex          # if you registered it with Claude Code
uv tool uninstall budgetdex          # or: pipx uninstall budgetdex
rm -rf ~/.budgetdex                  # the index and downloaded models ($BUDGETDEX_HOME if you set it)
```

Keychain items you created for connectors are not touched; delete them with `security delete-generic-password -s SERVICE`.

## Development

```bash
uv sync --all-extras && uv run pytest -q
uv run budgetdex bench eval/sample/questions.jsonl --corpus eval/sample/corpus
```

See [CONTRIBUTING.md](CONTRIBUTING.md) and [CHANGELOG.md](CHANGELOG.md). Licensed under the [Apache License 2.0](LICENSE).
