Normkompass

RAG with verifiable citations for German federal law.
Every answer points to the exact passage, for example "§ 14 Abs. 1 UStG". If the corpus does not support an answer, the service refuses instead of guessing.

CI status of the main branch License: MIT Language: TypeScript, strict mode Requires Node 24 or newer Database: Postgres with pgvector Specifications written with OpenSpec

The demo corpus is German federal law from gesetze-im-internet.de. This is a reference implementation, not a finished product; see "Limitations".

This README is also published as a website: https://sotream.github.io/normkompass/.

Contents

Overview

Use it

How it works in detail

Results and limits

Project

Status

Reference implementation, all planned v1 phases implemented: project scaffold, corpus ingest with a structure-aware parser for the demo laws, hybrid search with a retrieval evaluation and an embedding comparison (ADR 0002), and answer generation with code-checked citations and refusal. It is not a finished product. See "Limitations" for what is not known or not done, in particular that the Claude runs are one run per model on questions that Claude wrote and the owner reviewed, and that the default search is hybrid with BM25 and citation matching, chosen by a rule fixed before the runs (ADR 0004), after an earlier hybrid scored below vector-only (ADR 0003).

How it works

flowchart LR
  subgraph offline ["Offline: ingest and index"]
    law["gesetze-im-internet.de<br/>5 federal laws"] --> parse["Parse by structure<br/>§ → Absatz → Nummer"]
    parse --> chunks["Chunks with citation label,<br/>title and Stand"]
    chunks --> db[("Postgres<br/>pgvector + full text")]
  end
  subgraph online ["Online: POST /ask"]
    q["Question"] --> search["Hybrid search<br/>vector + BM25 + citation matching"]
    db -.-> search
    search --> model["Answer model<br/>Claude, Ollama or OpenAI-compatible"]
    model --> check{"Code check:<br/>is every quote a verbatim<br/>substring of a retrieved chunk?"}
    check -- "all citations verify" --> ok["Answer + citations<br/>(source, path, URL, quote) + Stand"]
    check -- "any citation fails" --> refuse["Refusal"]
    search -- "nothing retrieved" --> refuse
    model -- "declines, bad output or error" --> refuse
  end

The model proposes an answer with quotes; the code, not the model, decides whether it is shown. One failed citation turns the whole answer into a refusal. A worked example with a real answer and a real refusal is in docs/worked-example.md.

Results at a glance

What was measured Result
Default search on 75 paraphrase questions recall@5 0.960, MRR 0.900 on all 75; 0.946 and 0.901 on the held-out half (37), which was used to check the tuning (see Limitations); all 75 not significantly different from vector-only (0.960, 0.889)
Default search on 28 lexical questions (written to favor it) recall@5 0.857, MRR 0.720, against 0.679 and 0.536 for vector-only
Citation validity of a free hosted model (gemini-3.5-flash-lite, 4 runs) 0.940 to 0.976
Citation validity of Claude Opus 5.5 and Sonnet 5.5 (1 run each) 1.000 for both (241/241 and 168/168); a single run per model on 89 questions, 2026-11-07, not a ranking

Every figure comes from a recorded run in eval/results/; the charts below are generated from those files and checked in CI. The paraphrase and lexical questions were written by Claude, the same model that wrote the code, and the owner reviewed the 89 paraphrase questions; the sets are small, so read the whiskers (95% bootstrap intervals), not only the bars. Full tables are in "Retrieval results" and "Answer evaluation".

Retrieval on paraphrase questions

Retrieval on lexical questions

How this was built

The code, specs and documents in this repository were written by Claude (Anthropic's model, used through Claude Code), directed by the repository owner with a human in the loop. Work follows OpenSpec: every change started as a spec pull request that the owner read and merged before any implementation existed, and the implementation arrived as a separate pull request that the owner merged after review. The owner set the goals, the constraints and the acceptance criteria and decided at each gate. Commits are made under the owner's account. Who wrote the evaluation questions and corpus units is stated under "Limitations".

If you want to judge the engineering and the product thinking rather than take this page's word for it, these are the places where it is visible and checkable:

Output of this project is not legal advice and makes no promise that the law shown is current or complete.

Quick start

Requirements: Node 24, pnpm, Docker.

pnpm install
cp .env.example .env   # then set POSTGRES_PASSWORD
docker compose up -d   # Postgres with pgvector
pnpm build && pnpm lint && pnpm typecheck && pnpm test
pnpm ingest            # downloads the demo laws into .cache/ and prints a per-law summary
pnpm index             # embeds all units and stores them in Postgres (first run: model download, ~8 min)
pnpm eval              # same as pnpm eval:retrieval: recall@5 and MRR over eval/questions.jsonl; writes eval/results/
pnpm charts            # redraws docs/charts/*.svg from eval/results/ (pnpm charts:check verifies them)

The API (apps/api) exposes GET /health, POST /search with {"question": "...", "limit": 5} (ranked chunks with source, path, URL and Stand) and POST /ask with {"question": "..."}, which returns {answer, citations[{source, path, url, quote}], refused, stand}. /ask needs a configured answer model (see "Answer providers"); without it the endpoint answers 503 and sends nothing to the network.

pnpm ingest fetches five laws from gesetze-im-internet.de one request at a time (about 10 seconds), caches them, and reports units, skipped norms and the "Stand" of each law. Pass -- --refresh to download again. See ADR 0001 for the legal status of the data.

Corpus model

A law is split by structure: § → Absatz → Nummer. The retrievable unit is the Absatz; a § without Absätze is one unit. Sentences (Satz) are not split, so citations are precise to Absatz or Nummer, for example "§ 14 Abs. 1 UStG". A Nummer label such as "§ 14 Abs. 2 Nr. 1" locates the list item inside the Absatz and omits any "Satz" qualifier of the official form. The corpus is read through the CorpusSource interface in packages/corpus.

Process

Changes follow spec-driven development with OpenSpec: specs live in openspec/, decisions in docs/adr/. Validate with pnpm spec.

Chunks are the corpus units (Absatz, Nummer, or a whole norm). A unit longer than 1500 characters is split into parts at line or word boundaries; the parts keep the unit path. Each chunk is embedded with its citation label and title as a prefix ("§ 14 Abs. 1 UStG Ausstellung von Rechnungen ..."), while the stored text stays the original wording. The default search is hybrid: it merges three rankings with weighted Reciprocal Rank Fusion (k = 60): cosine similarity over the chunk embeddings (an exact scan; about 4,600 chunks, no ANN index), a BM25 ranking over the German-normalized words of each chunk (computed in the application, built at the first search), and, when the question names a citation such as "§ 14 Abs. 1 UStG", the chunks with that citation label. Query words that are German compounds are also split into parts known from the corpus vocabulary. Other configurations stay selectable and are measured: vector-only, Postgres full-text (query words OR-ed, or a strict AND query with fallback), a full-text weight, a filter for very common words. The default came from comparing them on a development half of the questions and confirming on a held-out half (ADR 0003, ADR 0004).

Embeddings come from multilingual-e5-small, run locally with transformers.js, so no text leaves the machine after the one-time model download. It was kept after comparing four local models (ADR 0002); a local reranker exists but is off by default.

Retrieval results

eval/questions.jsonl holds 75 German questions that the corpus answers and 14 that it does not. Each answerable question lists the expected units and the place in the corpus it was derived from. A script checks that every expected unit exists and that the words of each unanswerable question's topic (absent_terms) occur nowhere in the corpus; it flagged seven wrong guesses while the set was written. Seven questions are flagged needs_review; they were checked once in the same process that wrote the questions, which reworded three of them (see ADR 0003), and have not been reviewed by anyone else.

A returned unit counts as a hit if it is the expected unit or its parent Absatz or §. Recall@5 is the fraction of expected units hit in the top 5, MRR uses the first hit within the top 10. The 14 unanswerable questions are not used for these two metrics; refusal is evaluated with answer generation.

Embedding models in the same search

Table: paraphrase questions (eval/questions.jsonl, 75 answerable)
Date Commit Embedding model Search recall@5 MRR Index time Weights
2026-11-04 9d9d041 multilingual-e5-small hybrid: vector + BM25 + citation matching (default) 0.960 0.900 229 s 118 MB
2026-11-03 5c9212a multilingual-e5-small vector only 0.960 0.889 229 s 118 MB
2026-11-04 9d9d041 multilingual-e5-small hybrid: vector + BM25, no citation matching 0.960 0.907 229 s 118 MB
2026-11-03 5c9212a multilingual-e5-small hybrid: vector + Postgres full-text (older default) 0.907 0.748 229 s 118 MB
2026-11-03 5c9212a multilingual-e5-small Postgres full-text only 0.627 0.396 229 s 118 MB
2026-11-03 5c9212a multilingual-e5-base hybrid with Postgres full-text 0.920 0.736 364 s 279 MB
2026-11-03 5c9212a multilingual-e5-large hybrid with Postgres full-text 0.920 0.779 5246 s 562 MB
2026-11-03 5c9212a bge-m3 hybrid with Postgres full-text 0.893 0.746 16719 s 570 MB
2026-11-03 4a0f7f6 multilingual-e5-small vector + reranker (bge-reranker-v2-m3, top 20) 0.987 0.958 229 s 118 MB
Table: lexical questions (eval/lexical-questions.jsonl, 28 answerable: 10 exact terms, 9 numbers, 9 citation lookups)

Written to favor lexical matching and reported separately; they are not averaged with the table above.

Date Commit Search recall@5 MRR
2026-11-04 9d9d041 hybrid: vector + BM25 + citation matching (default) 0.857 0.720
2026-11-04 9d9d041 vector only 0.679 0.536
2026-11-04 9d9d041 hybrid: vector + BM25, no citation matching 0.607 0.538
2026-11-04 9d9d041 hybrid: vector + Postgres full-text (older default) 0.714 0.647
2026-11-04 fa54502 Postgres full-text only 0.536 0.428

External question set (written by other AI assistants)

To test the lexical results against questions this repository's author did not choose, four batches of 16 to 24 corpus passages (seed 20261107, every law in every batch) were given, with the instruction in eval/external/INSTRUCTIONS.md, to two assistants, each of which got all four batches and wrote its own questions on the same passages: Perplexity and Gemini 3.6 thinking, as reported by the repository owner (versions are not recorded and the repository cannot verify what produced a file). Perplexity's outputs ended with a "Sources" line, which suggests an interface with web search; for batch d Gemini's paste also contained its own code and a first draft, and only its final 16 lines are stored (see eval/external/raw/; everything else is stored as received). Of 164 lines, 144 became questions and 20, all Perplexity's, were rejected with a reason in eval/external/rejected.json (15 whose quoted term is not in the question verbatim, 1 copy of an existing question, and 4 "Sources" lines that are not JSON). 62 of the 144 are flagged needs_review because the quoted term also occurs in other passages, so the single expected passage is not the only defensible answer; 20 of Gemini's 38 flags are "number" questions whose "number" is a reference such as "Nummer 1" or "Absatz 2". These are model-written questions, not users' questions, each written while looking at the passage, so they quote its words and favor lexical matching. Two writers are not a sample of writers.

Cells show recall@5 / MRR; "unflagged" leaves out the needs_review questions.

Search (multilingual-e5-small) all 144 Perplexity 64 Gemini 80 Perplexity unflagged 40 Gemini unflagged 42
default: vector + BM25 + citation matching 0.979 / 0.837 0.984 / 0.830 0.975 / 0.843 0.975 / 0.814 1.000 / 0.952
vector only 0.903 / 0.727 0.953 / 0.753 0.863 / 0.705 0.975 / 0.796 0.976 / 0.858
vector + BM25, no citation matching 0.840 / 0.698 0.719 / 0.601 0.938 / 0.776 0.550 / 0.422 0.929 / 0.821
vector + Postgres full-text (older) 0.750 / 0.584 0.656 / 0.534 0.825 / 0.625 0.500 / 0.405 0.810 / 0.621

Result files are eval/results/2026-11-07-multilingual-e5-small{,-vector,-nocitation,-fts-nocitation}-external.json (commit b5d26fe; the first version of these files covered Perplexity's 64 questions only, and its per-question ranks are unchanged in the files above). Paired 95% bootstrap intervals of the MRR difference, default minus vector-only: +0.110 [+0.066, +0.157] on all 144 and +0.057 [+0.003, +0.116] on the 82 unflagged ones; by writer on the unflagged questions, Perplexity +0.018 [-0.063, +0.104] (not significant) and Gemini +0.094 [+0.028, +0.174]. Default minus the older hybrid: +0.253 [+0.184, +0.321] on all 144 and +0.127 [+0.049, +0.206] on the 91 term and number questions.

Reading it: on questions written by two other assistants the default is ahead of vector-only (on the unflagged questions for one writer significantly and for the other not) and clearly ahead of the older Postgres hybrid, including on exact terms and numbers, which agrees with ADR 0005 that the earlier gap in favor of the older hybrid was noise. The earlier observation that vector-only is slightly better on citation lookups did not replicate: it held for Perplexity's short "Was regelt § ...?" questions (MRR 0.743 against 0.815, 27 questions, not tested) and was reversed for Gemini's (0.962 against 0.912, 26 questions), whose citation questions also name content, so it depends on how the question is phrased. This set was not used to choose the default.

How to read these (details and paired bootstrap intervals in ADR 0002, ADR 0003 and ADR 0004):

Run a comparison with pnpm index --embedder <name> and pnpm eval:retrieval --embedder <name> [--questions eval/lexical-questions.jsonl] [--mode vector|hybrid|fts] [--lexical fts|bm25] [--no-citation] [--fts-query or|and] [--rerank] [--no-compound] [--fts-weight w] [--fts-max-share s] [--bm25-b b] [--no-keep-numbers] [--split dev|heldout], where the names are local-e5, local-e5-base, local-e5-large, local-bge-m3 and fake. Raw results are in eval/results/ and pnpm eval:compare a.json b.json gives the paired bootstrap. pnpm eval:diagnose shows, per question, where vector and full-text ranking place the expected unit, and pnpm eval:exact-terms compares the default with the older hybrid on the exact-term and number questions. The commit shown is the head of the pull request branch the numbers were measured on (a squash merge gives it a new hash). The runs are manual.

Weak spots, as measured with the default: 3 of 75 paraphrase questions have no expected unit in the top 10 (q030, q044, q057); on the lexical set 4 of 28 are not in the top 5. Among the paraphrase misses are general questions about the scope of a whole law, for example "Für welche Steuern gilt die Abgabenordnung?" (§ 1 Abs. 1 AO); the reason has not been analyzed.

CI runs a smaller eval on fixtures with a deterministic fake embedder (14 questions, thresholds recall@5 >= 0.7 and MRR >= 0.5; measured 0.786 and 0.652 in the default mode) against a Postgres service. It guards against regressions in the search code and says nothing about quality with a real model.

Bring your own corpus

Everything except the demo parser works on the CorpusSource interface (packages/corpus): name, loadDocuments() (read the raw material) and split() (turn one document into units with a stable id, a structural path, a citation label, a title and a URL). Index the units with indexUnits, search with HybridSearch, and score with the functions in packages/eval against your own questions.

examples/own-corpus is a complete, small example: a folder of .txt files where a line starting with # begins a section and each section is one citable unit. It is tested in CI (the adapter, and indexing plus a search query against Postgres). Run it, with Postgres from docker compose up -d:

pnpm example "Wie viele Urlaubstage habe ich?"   # fake embedder, no model download
EMBEDDER=local-e5 pnpm example "..."              # real embeddings

It writes to its own Postgres schema, so it never mixes into the law index. The example documents are invented text, not a real policy. The Markdown source under packages/corpus/test stays a test fixture.

Limitations

Answers and citations

POST /ask retrieves the 8 best chunks, gives them to Claude (through the Anthropic SDK) as numbered sources, and asks for a JSON object with an answer and citations that refer to sources by number. The code, not the model, then checks the result:

A refusal is refused: true, an empty answer, no citations and stand: null. It is returned when nothing was retrieved (the model is not called), when the model declines, when its output cannot be parsed, when verification fails, and when the model call fails. For an answer, stand lists the Stand of each cited law. The model id comes only from configuration. Corpus text and the question are passed as data and the prompt tells the model to ignore instructions inside them; the checks above do not depend on it.

The strict refusal rule trades recall for trust: an answer whose quotes are copied sloppily is refused even if its content is right. How often that happens depends on the model and has to be measured.

Answer providers

ANSWER_PROVIDER selects the model behind /ask and the answer eval:

There is no default model in the code for any provider. Keys go only in the git-ignored .env.

Citation verification and the refusal rule are identical for every provider. Results always name the provider and model; a local model's numbers say nothing about Claude and the other way round.

ollama pull llama3.1:8b                    # example; about 5 GB
# .env: ANSWER_PROVIDER=ollama and OLLAMA_MODEL=llama3.1:8b
pnpm eval:answers                          # 89 requests, runs locally

To use a free hosted model instead, create a key (for Gemini: Google AI Studio, "Get API key"), then in .env set ANSWER_PROVIDER=openai-compatible, ANSWER_BASE_URL=https://generativelanguage.googleapis.com/v1beta/openai/, ANSWER_API_KEY, ANSWER_MODEL (the available names change; GET <base url>/models lists them) and ANSWER_MIN_INTERVAL_MS=6000, and run pnpm eval:answers.

Answer evaluation

pnpm eval:answers runs all 89 questions through the full pipeline with the real model and reports citation validity (the share of proposed citations that pass verification), how often an answer cites an expected norm, and refusal precision and recall (with "refused" as the positive class). It sends 89 requests to the configured model. With claude that costs money, so it is a manual command; with ollama it is free but takes a while.

Results

Answer evaluation for five models

Table: answer evaluation runs
Date Commit Answer model Embedder Citation validity Cites expected norm Refusal precision Refusal recall
2026-11-02 abef35d (see note) ollama llama3.1:8b multilingual-e5-small 0.486 (69/142) 0.867 (of 30 answered) 0.237 1.000
2026-11-02 7971384 openai-compatible gemini-3.5-flash-lite @ generativelanguage.googleapis.com, 4 runs multilingual-e5-small 0.940–0.976 0.956–0.971 (of 66–69 answered) 0.609–0.700 1.000
2026-11-02 7971384 openai-compatible gemini-3.1-flash-lite @ generativelanguage.googleapis.com, 1 run multilingual-e5-small 0.851 (80/94) 0.966 (of 59 answered) 0.467 1.000
2026-11-07 327de90 claude claude-opus-5-5, 1 run multilingual-e5-small 1.000 (241/241) 0.986 (of 72 answered) 0.824 1.000
2026-11-07 327de90 claude claude-sonnet-5-5, 1 run multilingual-e5-small 1.000 (168/168) 0.972 (of 72 answered) 0.824 1.000

The first row is a small local model run on a laptop. Reading its numbers plainly: the pipeline never accepted a bad citation, but the model is a poor fit for the task. Of the 75 answerable questions only 30 were answered; 45 were refused, and all 14 unanswerable questions were refused (hence recall 1.0 and a low precision of 0.237). Refusal reasons across all 89 questions: citation-rejected 44, model-refused 7, no-citations 6, model-error 2. Most refusals come from the strict rule that any citation failing verification (usually a quote that is not verbatim) rejects the whole answer.

The Gemini rows are Google models through the free tier (hosted third parties; question and source text were sent to Google). gemini-3.5-flash-lite was run four times to see the spread: citation validity 0.955, 0.940, 0.954, 0.976; 66 to 69 of 75 answerable questions answered; refusal precision 0.609 to 0.700; all 14 unanswerable questions refused every time. The main weakness is over-refusal: about 6 to 9 answerable questions are refused per run, partly because a quote was not verbatim and partly because the model declined. No request failed. The raw per-run files are in eval/results/ (...-run2.json and so on; the unsuffixed file is run 1). gemini-3.1-flash-lite was clearly worse in its one run (more non-verbatim quotes, fewer answers). Hosted models can change or be retired without notice and runs are not guaranteed repeatable, so these are data points for this corpus and not a ranking. The commit 7971384 is the implementation branch before squashing, so it does not exist on main under that hash.

Not measured, on purpose or for lack of access: gemini-3.8-flash and gemini-3-flash-preview (so overloaded or slow on the free tier that no run finished in a reasonable time), gemma-4-26b-a4b-it (stopped, too slow on the free tier), gemma-4-31b-it (the endpoint returned an internal error), and every model of Mistral and Groq (no key; Groq's free tier also appears too small for a full run in a day).

Note on the commit: the recorded abef35d is a docs-only commit made before the provider code was merged to main (as 595c501). The run was made from a local build of that provider code, but the recorded revision does not identify it exactly, so treat the row as indicative and not exactly reproducible until the run is repeated on main.

Claude runs

Both Claude runs used the defaults (hybrid search, 8 retrieved passages, the shipped prompt) through the Anthropic API on 2026-11-07, one run per model, on commit 327de90. Cost, read from the organization's usage page before and after each run: Opus 5.5 $2.23 (about $0.025 per question), Sonnet 5.5 $0.88 (about $0.010); prices change, so this is the cost on that day. Of the 75 answerable questions, 72 were answered by each model; all 14 unanswerable questions were refused, so refusal recall is 1.0. Every proposed citation passed verification (Opus 241, Sonnet 168; Sonnet proposed fewer citations per answer). Both runs have 17 refusals, all with the reason model-refused: none was rejected by citation verification and no model call failed.

The two models refused the same three answerable questions, which is why refusal precision is 0.824 (14 of 17) for both. Re-running the search for them shows what is known: for q030 (which taxes the Abgabenordnung applies to) and q044 (who can be called in during an objection procedure) the expected unit was not among the 8 retrieved passages, so there the miss is in search and the refusal is consistent with what the model was given. For q027 (the deadline for a refund application) the expected unit was the top hit, and both models still refused; why is not established here.

What this shows: with these questions, Claude's citations were all verifiable and it refused every question the corpus cannot answer. What it does not show: which of the two models is better (one run each, a difference of one question out of 72), how stable the numbers are across repeated runs, or how Claude behaves on questions written by other people or on other laws. The raw files are in eval/results/answers-2026-11-07-claude-*.json.

CI runs the same pipeline on fixtures with a scripted stand-in model that never touches the network. It checks that the code and the metrics behave correctly (a faithful model scores 1.0, a model that misquotes or answers unanswerable questions is detected); it does not measure any model.

License

MIT, see LICENSE. The demo corpus is not covered by it: the laws from gesetze-im-internet.de are not protected by copyright (§ 5 UrhG), see ADR 0001.