diff --git a/README.md b/README.md index 1f0ee44..c5a57b9 100644 --- a/README.md +++ b/README.md @@ -1,154 +1,327 @@ # iglo.mem -Repository-local semantic search for Markdown. Prepare a snapshot when your -knowledge changes, then search it from an agent or a terminal. +`iglo.mem` is a repository-local semantic search CLI for Markdown. It is aimed +at developers and AI coding agents that keep durable project knowledge in Git, +especially under `.agent/knowledge` and `.agent/decisions`. + +The workflow is explicit: prepare a searchable snapshot after source changes, +then search that snapshot with a natural-language question. The CLI returns +ranked Markdown evidence as JSON. It does not write answers, modify Markdown, +or run model inference locally. + +## Is it a fit? + +Use `iglo.mem` when you want semantic retrieval beside a repository, with +worktree-local files and a small command-line interface. It can connect a +question to passages that use different wording, while keeping the published +snapshot inspectable and commit-able. + +The boundaries matter: + +- Preparation and non-empty search use OpenRouter. Document chunks, queries, + generated retrieval variants, and reranking passages leave the machine, and + provider usage may incur cost. +- Only Markdown below `.agent/knowledge` and `.agent/decisions` is indexed. It + is not a general codebase, arbitrary-file, or connector-based indexer. +- Search reads the last successful snapshot. It does not check whether current + Markdown is newer, and results can be stale after edits, moves, deletes, or a + branch change. +- There is no database, daemon, watcher, UI, answer generation, or local model. + The active vectors are loaded and ranked by the CLI for each search. +- Linux x86_64 is the only supported build target. Other platforms are + unverified. + +It is a poor fit when the data must stay offline, indexing must happen +automatically, one index must serve many worktrees, or you need broad source +connectors and a hosted retrieval service. + +## Install from source + +There is currently no tagged release. The supported distribution path is the +Linux x86_64 executable built from this repository or downloaded from a GitHub +Actions artifact. + +From the repository root: + +```sh +npx --yes bun@1.4.2 install --frozen-lockfile +sh scripts/build.sh +``` + +The build requires a C compiler and Node-API headers. Linux builds use +`/usr/include/node`; set `NODE_INCLUDE_DIR` to override that location. The +result is `dist/iglo.mem`. The executable includes Bun and the native lock +binding. It does not require Bun, Node.js, npm, or Git at runtime, but it does +need the target operating system's C runtime. + +The first build or check downloads about 11.43 MB of hash-pinned Qwen +tokenizer data into an ignored local cache. Later runs reuse the verified cache +and the executable embeds the data, so it does not download a tokenizer at +runtime. This is tokenizer data, not model weights. Builds also generate +`dist/THIRD_PARTY_NOTICES.txt`; distribute that file with the executable. See +the [third-party record](docs/third-party.md) for provenance and build history +requirements. + +The CI workflow packages `iglo.mem-linux-x64.tar.gz` for pushes and pull +requests. These artifacts expire after 14 days and are not releases. + +For source development in this repository, the launcher is: ```sh -iglo.mem init -iglo.mem prepare -iglo.mem search "How do refresh tokens work?" -iglo.mem status -iglo.mem gc +sh /absolute/path/to/iglo.mem/scripts/run.sh init ``` -Run commands from anywhere inside the target Git worktree. Every command emits -one JSON object to stdout; prompts and progress use stderr. Errors exit with -status 1. Initialization preserves existing configuration and Markdown. +The launcher runs the source CLI from this checkout. To operate on another +repository, use the compiled executable from inside that repository. + +## Quick start -## Credentials +Run the executable from anywhere inside the target Git worktree: -Run `iglo.mem init` in a terminal. If no key is available, it asks for an -OpenRouter key with input hidden and saves it to -`~/.config/iglo.mem/credentials.json`. Create a key at -. +```sh +cd /absolute/path/to/your-repository +/absolute/path/to/iglo.mem/dist/iglo.mem init +/absolute/path/to/iglo.mem/dist/iglo.mem prepare +/absolute/path/to/iglo.mem/dist/iglo.mem search "How do refresh tokens work?" +``` -This is one plaintext file shared by your repositories and worktrees. Its -permissions are private to your OS user. The key is never copied into the -repository. Cancellation or a failed save preserves the previous key. +`init` creates `.agent/memory.json` and the missing `.agent` directories. It +preserves existing configuration and Markdown. Add or edit Markdown in the +indexed directories, then run `prepare` again. A valid snapshot and its vector +files can also be committed and searched from a fresh worktree. -`OPENROUTER_API_KEY` overrides the saved key without changing it. Use -`iglo.mem init --reset-credentials` to replace the saved key interactively. -The tool trusts other processes running as your OS user; it is not a secret -vault. Keep your home and credentials directory outside Git repositories. +Every invocation writes one JSON object to stdout. Prompts and progress go to +stderr. Errors are JSON objects and exit with status 1. -Prepare and search never prompt. They need a key only when making an embedding -request. Empty prepared snapshots can be searched without a key or network. -Initialization does not test the key against OpenRouter. +## Commands -## Sources and freshness +`iglo.mem init [--reset-credentials]` -Only `.agent/knowledge/**/*.md` and `.agent/decisions/**/*.md` are indexed. -`.agent/inbox`, dependencies, build output, dotenv files and the index are -excluded. Source symlinks are rejected. Markdown is never modified. +Initializes repository storage and sets up credentials. It makes no provider +request and does not build an index. `--reset-credentials` must be run in an +interactive terminal. -Every file uses the same Markdown heading and paragraph/code-block processing. -Complete blocks are grouped toward a soft size target for focused search -results. There is no local file/chunk length rejection or truncation; long -indivisible blocks stay intact. Provider input limits still apply. If a provider -rejects an input, preparation fails and the prior snapshot remains available. +`iglo.mem prepare` -`prepare` sends missing or changed inputs to OpenRouter, in batches of up to 64. -Unchanged valid vectors are reused. The published snapshot lives at -`.agent/memory-index/snapshot.json`, with individual binary float32 vectors in -`vectors/`. Compatible valid orphans from failed preparation can be reused; -`gc` removes recognized artifacts not referenced by the current snapshot. +Scans the indexed Markdown, chunks it, builds the prepared BM25 index, reuses +compatible vectors, embeds missing or changed inputs, and atomically publishes +`.agent/memory-index/snapshot.json` plus binary vector files. A failed +preparation preserves the previous active snapshot. -`search` embeds only the query and reads prepared data. It does not read Markdown, -check freshness, refresh, or repair the index. Results contain up to eight files, -ranked by cosine similarity plus fixed lexical bonuses, with headings, source -line ranges, scores, snippets and a preparation timestamp. Locations describe -the prepared content and can be stale. Search can continue after source files -are removed or made unreadable. Query failure is an error, never a lexical fallback. +`iglo.mem search ""` -Run `prepare` after edits or when a new worktree needs a fresh snapshot. A valid -committed snapshot can also be searched as-is. Each worktree has its own index. -Concurrent preparation, loading and GC coordinate with a five-second lock wait; -a stopped process releases its lock through the OS. +Searches only the last published snapshot. It runs the retrieval pipeline +described below and returns up to eight evidence passages. Search never reads +current Markdown, checks freshness, repairs the index, or publishes files. -`status` reports the snapshot schema, lexical and embedding profiles, prepared -counts and missing referenced vectors without reading -sources or calling OpenRouter. Corrupt present data is an error. `gc` requires -valid metadata and all referenced vectors before deleting anything. It does not -use Markdown changes to decide which vectors to keep. +`iglo.mem status` -## Configuration and recovery +Reports stored snapshot provenance, document/chunk counts, vector availability, +and missing referenced vectors. It does not scan Markdown, call OpenRouter, or +report current-source freshness. -`init` creates `.agent/memory.json`: +`iglo.mem gc` + +Removes recognized vector artifacts not referenced by the valid active +snapshot. The snapshot, not current Markdown, is the deletion authority. + +### Common failures + +- `INDEX_NOT_READY`, `INDEX_INVALID`, or `INDEX_INCOMPATIBLE`: run + `iglo.mem prepare` in this worktree. +- `API_KEY_MISSING` or `CREDENTIALS_INVALID`: set + `OPENROUTER_API_KEY`, or repair credentials with interactive `init`. +- `SOURCE_INVALID`: check Markdown permissions, UTF-8 validity, and source + symlinks. +- `EMBEDDING_FAILED`, `EXPANSION_FAILED`, or `RERANK_FAILED`: check the key, + provider connectivity, model configuration, and input budgets. +- `SEARCH_TIMEOUT`: retry; the total search deadline has elapsed. +- `INDEX_BUSY`: retry after the other operation releases the worktree lock. + +## Sources and snapshots + +Only these recursive paths are scanned: + +```text +.agent/knowledge/**/*.md +.agent/decisions/**/*.md +``` + +`.agent/inbox` is created by `init` but is intentionally excluded because it is +for unverified observations. Entries such as `.git`, `node_modules`, `dist`, +`build`, dotenv files, and symlinks are excluded or rejected as appropriate. +Invalid UTF-8 and unreadable source entries fail preparation. Markdown is never +modified. + +Preparation normalizes line endings for indexing, preserves headings and code +fences, and records source paths, line ranges, heading ancestry, passage IDs, +and snapshot text. Chunks target a soft 500 Qwen body-token budget while +preserving complete Markdown blocks and respecting provider input limits. An +indivisible oversized block is split at source boundaries when necessary; text +is not silently discarded. + +Each worktree owns `.agent/memory-index`. Preparation, snapshot loading, and +garbage collection coordinate with a bounded OS lock. Compatible vector +receipts can be reused after an interrupted preparation. Publication happens +only after the new vectors and snapshot validate successfully. + +Run `prepare` after editing Markdown, switching branches, or creating a +worktree. Search does not know whether a snapshot is stale. If the snapshot is +valid, search can still return its stored evidence even when the current source +file has been removed or cannot be read. + +## Configuration + +`init` creates this file when it is missing: ```json { "project": "your-repository", - "embedding": { "model": "openai/text-embedding-3-small" } + "embedding": { + "model": "qwen/qwen3-embedding-8b" + } } ``` -Only the OpenRouter embedding model is configurable; the endpoint and source -roots are fixed. Changing model, project or chunking/profile rules requires -`prepare` again. Rotating the key does not require re-embedding. +The default embedding profile is Qwen3-Embedding-8B at 4096 dimensions through +OpenRouter. `embedding.model` may be changed to another configured OpenRouter +embedding model, but changing the model or input/chunking profile makes the +existing snapshot incompatible; run `prepare` again. The retrieval expansion +and reranking models are fixed by the current implementation. An optional +`retrieval.model` is accepted only for the supported Voyage reranker +`voyageai/rerank-2.5`. -- `INDEX_NOT_READY`, `INDEX_INVALID`, `INDEX_INCOMPATIBLE`: run `prepare`. -- `API_KEY_MISSING`: run interactive `init` or supply the environment override. -- `CREDENTIALS_INVALID`: repair the saved file/path/permissions, or use an override. -- `EMBEDDING_FAILED`: check the override/saved key, model, input limits and network. -- `INDEX_BUSY`: retry when the other command finishes. +The endpoint and source roots are fixed. No provider SDK, model discovery, or +local inference service is required. -A failed refresh does not publish partial results. API retries cover temporary -network failures, HTTP 429 and 5xx, honor Retry-After, and are bounded to four -attempts and a two-minute request budget. Permanent errors do not retry. +## Credentials and network use -OpenRouter and its serving provider receive document chunks during preparation -and query text during search. Do not put secrets in the indexed Markdown. -The tool does not install schedules, hooks, watchers, or background services. -For cron, configure your own working directory and use the saved key: +Create an OpenRouter key at +. In an interactive terminal, `init` +prompts for it with hidden input and saves it as plaintext at: -```cron -0 * * * * cd /absolute/path/to/worktree && /absolute/path/to/iglo.mem prepare +```text +~/.config/iglo.mem/credentials.json ``` -## Build and verification - -The supported build for this PR is Linux x86_64. Other platforms remain -unverified and are not advertised as supported. No tagged release is published -before PR approval/merge. - -The **Check and build Linux executable** GitHub Actions run attaches -`iglo.mem-linux-x64.tar.gz`, containing the single executable with its executable -permission preserved. Download it from the run's Artifacts section, then: +The directory and file use owner-only permissions. The saved key is shared by +repositories and worktrees for the same OS user. This is not a secret vault; +keep the home and credentials directory outside Git repositories. + +`OPENROUTER_API_KEY` takes precedence over the saved key and is never saved by +the CLI. Use `iglo.mem init --reset-credentials` to replace the saved key. +`prepare` and `search` never prompt. An empty, successfully prepared snapshot +can be searched without a key or network because it has no remote work. + +Preparation sends missing document embedding inputs to OpenRouter. A non-empty +search sends the original question to OpenRouter for query embedding, typed +query expansion, and Voyage reranking; generated variants are also embedded. +The reranker receives the complete contextual passages selected from the local +snapshot. OpenRouter and its serving providers therefore receive text from the +question and indexed documents. Do not put secrets in indexed Markdown. + +The CLI does not install schedules, hooks, watchers, or background services. +If you want periodic preparation, configure your own scheduler with an +absolute worktree path and the credential environment or saved key. + +## Retrieval behavior + +For a non-empty snapshot, `search` performs these stages: + +1. Embed the unchanged original question with the configured embedding model + (Qwen by default) and ask the fixed low-reasoning Luna expansion model for + up to two lexical variants, two vector variants, and one HyDE topic. +2. Combine the original vector and prepared BM25 searches with the valid + generated searches using reciprocal-rank fusion. Original hits are + protected, and soft file diversity fills a candidate set of at most 40. +3. Send the original question and complete candidate passages to Voyage + rerank-2.5 through OpenRouter. Keep scores at or above the current inclusive + cutoff and return at most eight passages. + +Expansion output is retrieval input, never evidence or an answer. Invalid +expansion, embedding, reranking, or timeout fails the whole search; there is no +partial result or lexical-only fallback. + +The total search deadline is 30 seconds, including lock acquisition, loading, +all remote stages, and output preparation. Current application envelopes also +limit Qwen requests to 32 inputs and 32,768 summed input tokens per batch, +Voyage reranking to 40 candidates, and displayed snippets to 400 Unicode code +points. Long questions or passages that exceed the complete-input budgets fail +with a JSON error rather than being silently truncated. + +Search output identifies the retrieval contract explicitly: -```sh -tar -xzf iglo.mem-linux-x64.tar.gz -./iglo.mem init +```json +{ + "query": "How do refresh tokens work?", + "responseVersion": 2, + "scoreKind": "ordinal", + "retrievalRevision": "qwen-luna-voyage-v2", + "preparedAt": "2026-09-07T12:00:00.000Z", + "results": [ + { + "score": 1, + "passageId": "sha256:...", + "source": ".agent/knowledge/authentication.md", + "heading": "Refresh tokens", + "startLine": 12, + "endLine": 28, + "snippet": "..." + } + ] +} ``` -PR artifacts expire after 14 days; rerunning the build creates a fresh download. -The native build needs a C compiler and Node-API headers; these are build-time -requirements. The executable embeds Bun and the small OS-lock binding. It does -not require Bun, Node.js, npm, Git or a lock executable at runtime. It still needs -the target OS C runtime. A missing Git executable does not prevent worktree discovery. +`score` is an ordinal rank value (`1`, `0.5`, `0.333333`, …), not a +probability or calibrated relevance score. `preparedAt`, paths, lines, and +snippets describe the stored snapshot and may no longer match current files. +The short displayed excerpt can omit a condition that appears elsewhere in the +full stored passage; use the returned source location to inspect the Markdown. + +## Alternatives and trade-offs + +- Plain text search such as `grep` or `rg` is a better fit for exact matches, + arbitrary files, no network dependency, or fully offline use. +- A note or search application is a better fit when you need a UI, automatic + indexing, many source types, or cross-repository management. +- A hosted or database-backed vector index is a better fit when one service + must serve many worktrees or a larger deployment. `iglo.mem` keeps derived + files beside each worktree and does not provide a scale guarantee. +- QMD is evaluated as an external comparator in this repository, not exposed + as an `iglo.mem` backend. The repository's report is corpus-specific and the + frozen release decision is `NO_ROLLOUT`; this README makes no quality, + latency, cost, or parity claim about either system. + +## Maturity and development + +This is a pre-release source/CI-artifact project with no tagged release. The +repository contains automated tests, Linux CI, terminal checks, and a +clean-machine check, but those checks do not establish general retrieval +quality or release approval. The retrieval-v2 evaluation records its limits in +the [held-out report](docs/evaluation/retrieval-v2-heldout.md) and +[release gates](docs/evaluation/retrieval-v2-release-gates.md); its decision is +`NO_ROLLOUT`. + +For the repository's checks: ```sh -npm exec --yes --package=bun@1.4.2 -- bun install --frozen-lockfile +bun run lint +bun run format:check sh scripts/check.sh sh scripts/build.sh python3 scripts/qa-terminal.py +python3 scripts/qa-clean.py +npx --yes bun@1.4.2 --no-env-file --no-install --config=/dev/null scripts/qa-cli.ts ``` -Build and check scripts prepare the pinned tokenizer JSON in an ignored local -cache. The first run downloads about 11.43 MB of tokenizer data from Hugging Face; -later runs verify the cache and work offline. Downloads are hash-checked before -publication. The standalone executable embeds this data and never downloads a -tokenizer at runtime. Before direct `bun test` or source development, run -`bun run tokenizers` once. Keep the generated cache for offline builds. - -On Linux the default header location is `/usr/include/node`; override -`NODE_INCLUDE_DIR` if needed. Run the resulting `dist/iglo.mem` from your worktree. Distribute it with generated -`dist/THIRD_PARTY_NOTICES.txt`; see the [license record](docs/third-party.md). -Builds also need Git and the pinned notice-archive commit available. -For source development use the absolute path to `scripts/run.sh`. The supported -launcher and compiled build disable repository dotenv and Bun preload loading. -Do not use bare `bun src/cli.ts` from an untrusted repository. - -Tests use disposable repositories, homes and dummy credentials. See -[reproducing verification](docs/verification.md) for CLI, terminal, clean-machine, -benchmark and live-provider checks, and [design decisions](docs/decisions.md) -for the reasoning behind credentials, chunking, snapshots and locking. +`scripts/check.sh` prepares the pinned tokenizer assets, builds the native +binding, runs lint, formatting, tests, and strict TypeScript checking. The +controlled CLI harness uses a local transport fixture and does not make paid +provider calls. The clean-machine check uses Docker and a network-disabled +runtime. Live-provider checks are separate, consume API credit, and should use +disposable repositories with non-sensitive Markdown. + +See [verification instructions](docs/verification.md), [accepted design +decisions](docs/decisions.md), [retrieval contracts](docs/retrieval-contracts.md), +and [retrieval-v2 design](docs/retrieval-v2-design.md) for the detailed +contracts and reproduction recipes.