- dredd-core v0.17.0. Every /search answer carries the contract's version/q/hits/truncated beside Insider's own keys (services/search_v1); format=v1 applies the contract's limit default and 2-character minimum and asks the fast sources only. Hit links are the console's own routes. - PDF hyphenation left U+0002 inside words (art. 483 k.c.). The DzU splitters strip C0 controls (tab/newline/CR kept); 0013 cleans the 226 articles already stored. Requested by Tobiasz under Alpaq92/Atrium#17. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
63 KiB
Insider
Polish and EU legal acts and case law, searched and fetched live at the official sources — the
Sejm ELI API, SAOS and EUR-Lex/CELLAR — over a REST API, an MCP server for AI assistants, and a
console. A module of the Dredd/Prowe family (/insider on the platform), or a standalone app.
Self-hosted and single-tenant, built on dredd-core — the shared substrate this app family installs as a dependency rather than copies.
What Insider does
| Source | Covers | Search | Text |
|---|---|---|---|
Sejm ELI API (api.sejm.gov.pl/eli) |
Dziennik Ustaw, Monitor Polski | title (inflection-aware, see below), publisher, dates, in force — no full text | text.html → sanitised text; PDF-only (every act since 2025) → the PDF's text layer at once, OCR only for scans |
SAOS (saos.org.pl/api) |
Polish courts (common, SN, TK, administrative, KIO) | full text, case number, court, dates — slow: one request, 18 s read timeout, never retried | the judgment's HTML → sanitised text |
EUR-Lex / CELLAR (publications.europa.eu) |
EU regulations, directives, decisions, consolidated texts; CJEU case law | SPARQL: Polish title (prefix-stemmed), CELEX, dates, in force — no full text | CELLAR content negotiation, Polish first, English fallback; validity dates, newest consolidated version, article outline |
Polish inflection in title search
Neither ELI nor CELLAR searches text, and both match titles literally: "ochrona danych osobowych"
never finds "Ustawa … o ochronie danych osobowych" or the GDPR's "w sprawie ochrony osób
fizycznych …". Insider therefore stems the query with a small in-house Polish suffix stemmer
(integrations/plstem.py, Apache-2.0 — no permissive Polish stemmer with clearly licensed code
and data was found): ELI gets the light stem of the longest word (osobow), Insider reads a
window of 500 titles and keeps those containing the stems of all the words; CELLAR gets each
word as a Virtuoso prefix match ("ochron*" AND "danych" AND "osobow*") — but only a stem of 5+
characters; a shorter one goes in as its spelled-out case forms (("praca" OR "pracy" OR …)), the
commonest legal words (umowa, ustawa, prawo, art, …) are dropped unless they are all there is, and
the text-index match runs first in a sub-select capped at 1,000 titles. "umowa o pracę" used to time
out on "prac*" joined to every matching title; now it answers in ~1 s. CELLAR is asked for acts
(sector 3) and judgments (sector 6) in two queries, each with its own limit — in one newest-first
query the year's judgments filled the page and no EU act was ever shown.
Filters are scoped by kind
court (and case_number) narrow judgments only; publisher (DU, MP, EU) and in_force
narrow acts only. With kind=all a court never drops acts and a publisher never drops judgments;
the answer's filter_scope says which kind each set filter applied to, and a filter that does not
concern a source's kind is not reported in its unsupported_filters. The console shows the court
only under "Orzeczenia" and publisher + "Tylko obowiązujące" only under "Akty", and clears (with a
hint) whatever the newly chosen kind does not show.
LIVE mode
Insider runs in LIVE (federated) mode: every search fans out to the applicable sources at once
(connect 3 s / read 8 s per source, ~10 s overall, stragglers cancelled) and comes back with a status
line per source — ok | timeout | error | skipped | disabled | circuit_open, its latency, its total
and the filters it could not apply (unsupported_filters, e.g. ELI's full_text: it searches
titles). Acts and judgments come in separate groups, newest first, de-duplicated (acts by ELI/CELEX
id, judgments by case number + court + date). Pagination across sources is an opaque HMAC-signed
cursor; an edited cursor is refused.
There is no local copy of the sources — only a cache of what people fetched (Postgres
source_cache + an in-process LRU, single-flight per key): act metadata 24 h, act text kept per
changeDate, judgments 7 days, searches 15 minutes, "not found" 1 hour. Expired rows are deleted
every INSIDER_CACHE_PURGE_SECONDS (default 3600, 0 = off) by a task in the backend's lifespan; a
Postgres advisory lock lets only one worker purge at a time, the others skip that round.
ELI searches are ordered server-side (sortBy=change&sortDir=desc — the spec offers no
announcement-date column), so offset pages slice one ordering.
Set on the platform — two settings an operator must fill in, each logged as a warning at start-up while empty (the warning names the setting, never a value):
| Setting | Why |
|---|---|
INSIDER_CONTACT |
an e-mail or URL in the User-Agent, so the sources' operators can reach you |
INSIDER_CURSOR_SECRET |
the HMAC key of pagination cursors (a secret; openssl rand -hex 32); empty = a random key per process, so cursors break across workers and restarts |
INDEXED mode (Phase 2) — full text of the acts, and a local judgment index
ELI and EUR-Lex search only titles, SAOS searches full text — so without an index a content
query ("najem okazjonalny", "przekroczenie prędkości") finds judgments and no act at all. INDEXED mode
fixes that with local datasets in Postgres and an embedded full-text index, tantivy (tantivy
0.26.2 on PyPI, MIT; no server, no JVM), on disk under INSIDER_INDEX_DIR (default
<DATA_DIR>/index). Text is analysed in Python per language (see Language analysis below:
dictionary lemmas from sjp.pl first, the in-house plstem stemmer for words the dictionary does
not know), one index document per article (acts) or per section (judgments), hits grouped per act / judgment, the
act's title weighted ×3 and the query words side by side ×2.
| Dataset | What | How |
|---|---|---|
dzu_md |
PolskiAgentW/dziennik-ustaw-md (CC0 data, eli2md MIT): Dz.U. from 2025, PDF-only older acts, and ~4,900 consolidated texts (t.j.) 2012–26 |
on INSIDER_DZU_MD_SCHEDULE (07:15 Warsaw — after the upstream bot's ~05:00 UTC commit): one ~1 KB request for the branch head; a new commit fetches index.csv and only the acts whose PDF checksum / converter / conversion time changed, pinned to that commit, ≤ INSIDER_DZU_MD_RATE req/s, one at a time |
eli_inforce |
every act in force (inForce=1, types INSIDER_ELI_INFORCE_TYPES, base acts only) with its current consolidated text |
daily: ELI's listing, then per act whose changeDate moved one metadata request; the text (text.html, else the PDF's text layer) only when no dataset has it yet. Older t.j. are flagged superseded — kept, never searched (for every act held in several texts, whichever dataset holds them). Waits for dzu_md's first full pass, then starts; an interrupted pass resumes ~10 min later |
saos_dump |
SAOS's dump API (/api/dump/judgments) — metadata + sanitised text in sections |
the first full import only inside INSIDER_SAOS_DUMP_FIRST_WINDOW (23:00–05:00 Warsaw, several nights), then a daily delta on INSIDER_SAOS_DUMP_SCHEDULE; one request in flight, INSIDER_SAOS_DUMP_PAUSE_SECONDS between pages, resumable from the stored cursor; the next pass asks sinceModificationDate = when the previous one started |
cellar |
EU regulations, directives and decisions in force (CELEX sector 3, resource_legal_in-force), each with the text of its newest consolidated version (0…-YYYYMMDD), Polish — English when there is no Polish text, the language recorded |
the Publications Office's anonymous CELLAR (no EU Login account — it replaced the planned EUR-Lex dump): SPARQL keyset-paged listing, the 303 → resource/cellar text fetch, one request in flight at INSIDER_CELLAR_RATE (≤ 2/s, every hop counted). A full pass on INSIDER_CELLAR_FULL_SCHEDULE (Sundays; acts it no longer lists are marked out of force — kept, never searched), a delta on INSIDER_CELLAR_SCHEDULE (daily) (works whose CELLAR lastModificationDate, or a consolidated version's, moved since the last pass). Cursor saved after every page |
cellar_caselaw |
CJEU judgments (CJ, TJ) dated from INSIDER_CELLAR_CASELAW_FROM — off by default (INSIDER_CELLAR_CASELAW) |
the same channel and cadence; cut into ~12k-character pieces |
When it updates. Every dataset has its own cron variable, read in INSIDER_SCHEDULE_TZ
(default Europe/Warsaw, DST-aware); several expressions may be joined by ;; an invalid one
refuses to start, naming the variable; a run missed while the box was down happens once at the next
tick. Everything updates once a day at 05:00 Polish time, except dziennik-ustaw-md at 07:15 (its bot
commits around 05:00 UTC, so 05:00 Warsaw would always fetch the day before):
| Variable | Default | What |
|---|---|---|
INSIDER_SCHEDULE_TZ |
Europe/Warsaw |
the zone of every schedule and of the SAOS first-import window |
INSIDER_DZU_MD_SCHEDULE |
15 7 * * * |
dziennik-ustaw-md: the branch head, then only what changed |
INSIDER_ELI_INFORCE_SCHEDULE |
0 5 * * * |
ELI in-force acts: the listing, then only acts whose changeDate moved |
INSIDER_CELLAR_SCHEDULE |
0 5 * * * |
CELLAR acts: the delta |
INSIDER_CELLAR_FULL_SCHEDULE |
0 5 * * 0 |
CELLAR: the full listing pass (finds acts that left force) |
INSIDER_CELLAR_CASELAW_SCHEDULE |
0 5 * * * |
CJEU case law (when on): the delta |
INSIDER_SAOS_DUMP_SCHEDULE |
0 5 * * * |
SAOS: the daily delta, after the first full import |
INSIDER_SAOS_DUMP_FIRST_WINDOW |
23:00-05:00 |
SAOS: the first full import runs only in this window |
INSIDER_INDEX_REBUILD_SCHEDULE |
0 5 * * * |
rebuilding an index of another format / analysis (the old one answers meanwhile); a missing index builds at once |
INSIDER_EMBED_SCHEDULE |
0 5 * * * |
the embedding pass behind hybrid search (new / changed parts only; see Models) |
A delta writes only the changed documents into the index (delete by group, add, commit) — never a full rebuild. The Źródła page shows each dataset's last and next run. A notice ("Indeks aktów: aktualizacja w toku — wyniki z wyszukiwania na żywo", "… dane z dnia X …") appears only when a local source truly cannot serve (no index yet, a first import running, or data past its staleness threshold) — never during a delta or a rebuild, when the previous index answers.
How search uses it. A local source answers only when its index is built and its dataset has
finished a first full import and synced within the staleness threshold (INSIDER_DZU_MD_STALE_HOURS,
INSIDER_SAOS_INDEX_STALE_HOURS); otherwise its status line says skipped with the reason, and the
live sources answer exactly as before.
- Polish acts:
dzu_md(both act datasets, one index) answers beside ELI — its hits first, in relevance order, at article level (extra.articles[]: number, snippet); ELI's title hits follow for whatever the index does not hold. ELI stays authoritative for status and the current t.j.: a hit takes them from ELI's cached answer when there is one (no extra request in a search), and opening the act asks ELI as before. The text of a PDF-only act comes from the mirror. Every mirror result carriesextra.disclaimer"nieoficjalna konwersja; tekstem wiążącym jest PDF w Dzienniku Ustaw",source_pdf(the binding PDF),eli_urlanddataset_url. - Judgments:
saos_indexstands in for live SAOS when it covers the whole query (words or a case number; a court type, not a court's name — the dump has no common-court names) — then the 30-second live call is not made, and a judgment opened is read from the dump copy. Otherwise live SAOS answers, progressively, as before. The Supreme Court notice stays. - EU law:
cellarstands in for live CELLAR's title search for the kinds it holds ready and fresh (INSIDER_CELLAR_STALE_HOURS) — acts, and judgments whencellar_caselawis on. An all-kinds search with case law off asks live CELLAR for the judgments only. Hits are full text at article level ("Artykuł N", annexes), with the attribution "© European Union, https://eur-lex.europa.eu …", the conversion note (text_note), the EUR-Lex link of the act and of the consolidated text indexed (extra.text_celex,text_url); opening the act or its text reads the local copy. A CELEX or case-number lookup, anin_force=falsefilter and a stale index go live as before. The SPARQL shapes and the HTML structure pass are vendored from tseidl/eurlex-builder (MIT) intoapp/integrations/cellar_builder/and adapted (Polish headings, the in-force filter, keyset paging, the delta, stdlib parsing throughSourceClient) — see CREDITS.md. sources[]says which source answered (served_by: index | live) and each dataset's freshness;GET /sources/datasets(the console's "Źródła" panel) shows per dataset the last sync, commit or cursor, document count, last error, andrunning | idle | off.
Off switches: INSIDER_INDEX_ENABLED=false (the default) is LIVE only — nothing downloaded,
nothing opened. With it on, each importer has its own switch (INSIDER_DZU_MD_SYNC,
INSIDER_ELI_INFORCE_SYNC, INSIDER_SAOS_DUMP_SYNC, INSIDER_CELLAR_SYNC,
INSIDER_CELLAR_CASELAW). Importers run as lifespan tasks that wait first (start-up never imports)
and take a per-dataset Postgres advisory lock (the two Polish act datasets share one, and so do the
two CELLAR ones: each pair writes one index), so several workers never import the
same dataset twice. The index is disposable: lost with its volume, it is rebuilt from Postgres.
Disk (measured on a 30-act / 20-judgment sample, 2026-10-21, then scaled): acts ≈ 0.6 GB in
Postgres + 0.1–0.3 GB of index; the full SAOS dump (~450k judgments) ≈ 10–14 GB in Postgres + 4–6 GB
of index. First imports: dzu_md ~7.2k files ≈ 30–60 min; eli_inforce ≈ 2–3k acts in force, ~20–40
min; saos_dump ≈ 4.6k pages of 100 → about 8–12 nights in the default 6-hour window. cellar
(counted live 2026-10-21): 35.1k R/L/D works in force (30.4k with a Polish expression; 5.4k have a
consolidated version) → ~76k requests ≈ 21 h at 1 req/s (≈ 11 h at 2); measured on 9 large acts
(GDPR, DSA, AI Act…) 1.16 M characters → 0.9 MB of Postgres and 0.39 MB of index, so ≈ 0.6–1 GB +
0.2–0.4 GB for the whole set. Case law since 2000: ~25.5k CJ/TJ judgments with a Polish version.
Language analysis — lemmas, a legal thesaurus, partial matches
Every word reaches the index through integrations/analysis.py: one Analyzer per language in a
registry keyed by ISO code and chosen per document (acts and SAOS judgments are pl; a CELLAR
text records its language, so an English fallback text gets en). A Polish word goes to its
lemma through a dictionary — spółki, spółce, spółek → spolka; sądzie → sad;
dzieci, dziećmi → dziecko; najmu → najem; szedł, idzie → isc — and a word the
dictionary does not know falls back to plstem. Diacritics are folded on both sides, as before, so
"spolki" still finds "spółce".
- The dictionary is sjp.pl's inflection list ("Lista słów z odmianami",
https://sjp.pl/sl/odmiany/), which sjp.pl offers under a choice of GPL 2, LGPL 2.1, CC BY 4.0
or Apache 2.0 — Insider takes it under CC BY 4.0 (credit in
CREDITS.md). It is never committed: the image build downloads the current archive (two requests) andscripts/build_lexicon.pyturns it intolexicon/pl.lex, a 60 MB sorted form → lemma file read through mmap (≈7 MB of heap, ~25 µs per uncached lookup, cached after). Changes made to the data: proper names and multi-word entries dropped; negated "nie…" forms under a positive headword dropped (they keep plstem's stem, so niewykonanie never meets wykonanie); lower-cased and diacritic-folded; where a headword's whole paradigm is listed inside another's (the verbal noun wypowiedzenie inside the verb wypowiedzieć), its forms keep their own lemma. Without network at build time the image still builds and search falls back to plstem. - Ambiguity: a form with several lemmas is indexed as one token naming them all
(
mam→mam|mama|mamic|miec, at most 4) at its own position — phrase and proximity are unchanged — and a query word asks for each of its lemmas OR every such token that names one. - A legal thesaurus (
app/integrations/thesaurus/pl.tsv, query-side only, lemmatised through the same analyzer): everyday words → the words statutes use (parkowanie → postój, zatrzymanie pojazdu; niedozwolony ↔ zabroniony; rozwód ↔ rozwiązanie małżeństwa; mandat → grzywna …). A variant of the query weighs half the words as typed. Small and reviewed by hand — the file's header says how to add a line; no mined synonyms. - Partial matches: every content word must match. Only when nothing does, the index answers
with parts holding at least 60 % of them — each result says
extra.partial, and the answer carries the notice "Wyniki częściowe — nie wszystkie słowa zapytania występują w tekście". Never mixed silently with full matches. - A deploy that changes the analysis (
textindex.FORMAT, the lexicon) keeps the previous index answering — read with the analysis it was built with — until the rebuild is swapped in; the status line says "indeks przebudowywany — odpowiada poprzedni" and Źródła "tak (przebudowa w toku)".
Adding a language = a DataPackage in analysis.PACKAGES (source page, archive name, licence
and the phrase its README must contain, parser) + analysis.register("xx", …) (fallback stemmer,
stopwords, normalisation) + optionally thesaurus/xx.tsv. Nothing in the indexing code changes.
Alternative backends — optional, not implemented, nothing of them bundled. Each would be one
more Lemmatizer (ident, lookup(), groups) behind the same interface, and only under a
permissive licence (MIT, BSD, Apache-2.0, ISC, 0BSD, PSF, CC0, CC BY — never GPL/LGPL/AGPL/SSPL,
CC BY-SA or NC, for code, data and transitive dependencies alike):
- Morfeusz 2 (IPI PAN) — the best morphological analysis of Polish. The engine is declared BSD-2-Clause; its dictionaries (SGJP, PoliMorf) are published separately with their own terms, which must be verified at the source before any use; no aarch64 wheel on PyPI (the box would build it). Usable only if engine AND dictionary are permissive.
- Hunspell — a native engine, tri-licensed MPL 1.1 / GPL 2 / LGPL 2.1 (copyleft: not usable under the permissive-only rule), affix-rule stemming, slower per word; its pl_PL dictionary comes from sjp.pl itself, so it adds nothing the inflection list does not already give.
- MySpell — obsolete, superseded by Hunspell; not an option.
Models — hybrid search, reranking, query rewriting, cited answers
Search can use language models, every one optional and pluggable. Three narrow interfaces
(backend/app/ai/base.py), each picked by one config string (backend/app/ai/__init__.py):
| Interface | Does | Backends (INSIDER_EMBEDDER / INSIDER_RERANKER / INSIDER_GENERATOR) |
|---|---|---|
Embedder |
texts → unit vectors | local:<hf repo>[@<onnx file>] · openai-compat:<base_url>#<model> · ollama:<model> · none |
Reranker |
(query, passages) → scores | local:<hf repo>[@<onnx file>] · none |
Generator |
system + question → text | anthropic[:<model>] (default claude-sonnet-5-5) · openai-compat:<base_url>#<model> · ollama:<model> · provider:<name>[#<model>] · none |
local: runs on CPU with ONNX Runtime + tokenizers (no torch); the ONNX file and tokenizer.json
are downloaded once into INSIDER_MODEL_CACHE_DIR (default <DATA_DIR>/models;
INSIDER_MODEL_OFFLINE=true forbids downloads — pre-seed the directory). openai-compat: is any
server speaking /chat/completions (and /embeddings): OpenAI, Mistral, vLLM, llama.cpp's server,
LM Studio, a Bielik deployment. provider: takes the provider from the platform's shared list
(dredd-core model_providers, written in Atrium): address, models and policy (who may use it, EU-only)
from that row, the key from model_provider_key — readable only when the hub opted this module in
as a key reader, decrypted with the platform's MODEL_PROVIDER_SECRET. Plain httpx, no vendor SDK.
- Hybrid search — on with the index. Every article (acts) / part (EU acts; SAOS sections with
INSIDER_SEMANTIC_DATASETS=dzu_md,cellar,saos_dump) gets an embedding; a query searches BM25 and the nearest parts, grouped per act the same way, fused by reciprocal rank fusion (k=INSIDER_RRF_K, the vector list weightedINSIDER_VECTOR_WEIGHT). It finds the act for a question that shares no word with it ("czy szef może mnie zwolnić od ręki" → Kodeks pracy). Where the vectors live: files beside the tantivy index (<dataset>.vec/: append-only segments, each a float16.npyopened withmmap+ its metadata), not pgvector — they are as disposable as the index and rebuilt from the same Postgres rows, so nothing needs an extension on the managed database, no new table, grant or migration, and the other modules carry nothing. Search is exact,16384rows at a time with a running top-k, scoring only the rows the filters keep (81% of the acts' parts are superseded texts): ~0.3-0.8 s over 559k parts on the box, and a search's own memory is one chunk (~25 MB) whatever the store's size — the mapped vectors are page cache the kernel reclaims. The query's thesaurus variants (integrations/thesaurus/pl.tsv) are embedded beside it and a part scores by the best of them. A store of the old format (compressed float32shard-*.npz, loaded whole: 2.9 GB for one search on the box) is converted once, shard by shard, when the embedding loop starts (~5 s for 559k parts); until then search is BM25 alone. The local model is loaded from a memory-mapped copy (<model cache>/<repo>/mapped/, written once in a child process): its weights stay file pages instead of a heap copy (e5-small: ~340 MB anonymous memory with the tokenizer, was ~790 MB). One hybrid search process on the box: ~830 MB peak RSS of which ~360 MB reclaimable file pages; warm 0.3-0.8 s, the first one ~3.6 s (model load + opening the store). The embedding job (services/semantic.run_embed_loop, a lifespan task) runs onINSIDER_EMBED_SCHEDULE(cron inINSIDER_SCHEDULE_TZ, default0 5 * * *, validated at start-up like the importers' schedules; a pass that did not finish resumes at the next tick), embeds only new or changed parts (a text fingerprint per part), carries flag changes (a superseded t.j.) without re-embedding, deletes what is gone, writes a segment every 1,024 vectors (resumable), pausesINSIDER_EMBED_PAUSE_SECONDSbetween batches ofINSIDER_EMBED_BATCH, and takes its own advisory lock per index. It is also where a local model is downloaded — a search never downloads: until the files are on disk, search is BM25 alone. - Reranking — built, OFF by default. The fused top
INSIDER_RERANK_TOP(20) are re-ordered by a cross-encoder over each act's best article, its order blended with the fused one by RRF (the cross-encoder sees one passage, not that a code outranks an amending act: used alone it lost two of the eleven regression queries). Off by default because on CPU the default candidate, bge-reranker-v2-m3 int8, costs ~25 s per query for no measured gain over hybrid; setINSIDER_RERANKER=local:onnx-community/bge-reranker-v2-m3-ONNX@onnx/model_quantized.onnxon a machine that can afford it (the embedding job then downloads and warms it). - Query rewriting — off. With a generator and Administracja → Modele → "Przepisywanie zapytań"
on, the first page of a search also asks the model to restate the question in statute vocabulary
(+ up to three candidate acts), searches that too and fuses the two result lists; the answer
carries
rewrite: {used, query, acts, model}(or{used: false, error}). - Cited answers — off.
GET /api/v1/answer?q=…and the MCP toolanswer_question, only with "Odpowiedzi z cytatami" on: retrieval (rewritten) → the matching articles / sections as numbered passages → the model answers only from them, every sentence ending in[n]. Sentences that cite nothing (or a passage that does not exist) are dropped; nothing left, or the model'sBRAK_PODSTAW, is a refusal (refused: true).citations[]names each passage: act + article or judgment signature + court, with theofficial_url.lang=pl|enpicks the answer's language.- The prompt is data (
backend/app/ai/prompts/answer.json): the rules plus two worked examples per language — one grounded answer, and one refusal although the right act is among the passages (the passage does not say what is asked). tobayah/legal-memory found that a ban in the system prompt alone did not stop invented article content; that second example did. - The graph widens the passages, never replaces them. After retrieval, up to
INSIDER_ANSWER_GRAPH_EXPAND(4; 0 = off) articles one hop away inlegal_ref— what the retrieved articles cite and what cites them — are appended, markedvia: graph:*, after the retrieved ones. Only while the graph is complete by the same guard asrank_prior(RankPrior.active); otherwise skipped.graph_expansion: {used, added, cap, skipped?}says which. - Every sentence is verified (
services/grounding.verify) and dropped on the first rule it fails:no_citation;source_out_of_range; an art. / § / ust. number, a date, or an act number (2016/679,poz. N, a case signature) not in the passage it cites (invented_*when no passage has it,miscited_*when another does — the whole context is searched first, because Polish amending acts quote whole EU acts in their titles); andlow_support: fewer thanINSIDER_ANSWER_MIN_SUPPORT(0.35) of its content words, lemmatised by Insider's analyzer, are in the cited passage — which catches an invented description of an act that IS among the sources (Polish answers; an English one is not measured,support_checked: false). Nothing left → refused. The response (and the MCP result) carriesverification: {passed, flagged[] (sentence, rule, detail, action), kept, sentences, model_refused, min_support}. - Optional by design. The MCP search / resolve / graph tools serve the facts to a client that
is itself a better reader;
answer_questionis for clients that want Insider to answer. python backend/tests/answer_eval.pyruns a generator that misbehaves on purpose (invents an article, cites the wrong passage, answers with no support …) and checks each is caught; real questions with the article an answer must cite run with--liveagainstINSIDER_GENERATOR.
- The prompt is data (
Questions leaving the machine. A generator is external unless it is a server on localhost (or
ollama/host.docker.internal) or a local platform provider. An external one is refused until an
administrator turns on "Pytania mogą trafiać do modelu poza tym serwerem" (ai_external_allowed):
with it on, people's questions are sent to that provider. The three switches are audited settings;
the model choice itself stays in the environment.
Each worker keeps the three switches, and each person's moderator answer (keyed by user id, never
shared), for INSIDER_AI_SWITCH_CACHE_SECONDS (30; 0 = read on every search). Saving the settings
drops the switches at once in the worker that saved them; other workers pick the change up within
that TTL, and a moderator promoted or demoted at the hub is seen within it too.
# fully local, everything on (nothing leaves the box)
INSIDER_EMBEDDER=local:intfloat/multilingual-e5-small
INSIDER_RERANKER=local:onnx-community/bge-reranker-v2-m3-ONNX@onnx/model_quantized.onnx
INSIDER_GENERATOR=ollama:SpeakLeash/bielik-11b-v2.3-instruct:Q4_K_M
# Bielik via Ollama on the same host (still local)
INSIDER_GENERATOR=ollama:SpeakLeash/bielik-11b-v2.3-instruct:Q4_K_M
INSIDER_OLLAMA_URL=http://localhost:11434/v1
# Mistral (OpenAI-compatible API; external — needs ai_external_allowed)
INSIDER_GENERATOR=openai-compat:https://api.mistral.ai/v1#mistral-small-latest
INSIDER_GENERATOR_API_KEY=...
# Claude (Messages API; external)
INSIDER_GENERATOR=anthropic:claude-sonnet-5-5
INSIDER_ANTHROPIC_API_KEY=...
# a provider the platform's administrator connected in Atrium
INSIDER_GENERATOR=provider:Bielik#bielik-11b-v2.3
MODEL_PROVIDER_SECRET=... # the hub's
Model weights: the default embedder multilingual-e5-small (MIT), the suggested reranker bge-reranker-v2-m3 (Apache-2.0; its int8 ONNX export) — ~0.5 GB each on disk; the embeddings ≈ 1.5 KB per part in RAM. Never defaulted: weights under restrictive terms (Llama community, Gemma, Mistral MRL / non-production, CC-BY-NC) — an operator may configure them, under those terms.
Measured on tests/search_eval.py (2026-10-21, a developer CPU; top-3):
| regression queries | 5 plain-language questions | per query | |
|---|---|---|---|
| BM25 with lemmas + thesaurus | 12/12 (recall 2/2) | 1/5 | ms |
hybrid (--hybrid) |
12/12 (recall 2/2) | 5/5 | + ~17 ms (query embedding) |
| hybrid + rerank top 50, rerank alone decides (before lemmas) | 9/11 | 4/5 | ~1 min |
hybrid + rerank top 20, blended (--semantic, before lemmas) |
11/11 | 5/5 | ~25 s |
Off switch for all of it: INSIDER_SEMANTIC=false.
SAOS: user-initiated live queries only
SAOS's robots.txt disallows /api/. Insider therefore uses SAOS only for queries a person
starts — a search, a click on a judgment, an MCP tool call made for a user — one request at a
time, at a low rate (INSIDER_RATE_SAOS=1 req/s, concurrency 1, both capped at 2) and with an
identifying User-Agent (Insider/<version> (+INSIDER_CONTACT)). There is no crawling, no dumps, no
bulk copying, no prefetch and no warm-up job; the cache keeps what a person fetched for its TTL, and
SAOS texts never enter doc_text. INSIDER_SOURCE_SAOS=false switches it off entirely (it then
reports disabled and nothing is sent).
(The owner has since approved SAOS's dump API for the local judgment index — a separate, scheduled, incremental channel used only by the ingestor; see "INDEXED mode" above. The live search described here is unchanged, and never falls back to the dump endpoint.)
SAOS is slow and incomplete — said, not hidden. Every SAOS query took 22–30 s when measured
(2026-10-21), so SAOS gets one request with a 35 s timeout, never a retry, and its own budget
(INSIDER_SLOW_SOURCE_BUDGET_SECONDS, 40). A progressive=true search answers with ELI and
EUR-Lex at once and lists SAOS under pending with a ticket (HMAC-signed, bound to the person,
five minutes); GET /search/pending?ticket= returns SAOS's page when it is ready — it was already
being fetched in the background, through the same single-flight cache. The console does exactly this
("ładowanie…" in the status line, then the judgments). MCP's search_judgments waits by default
(wait_for_slow=true); false returns at once with pending: ["saos"], and a repeat answers from
the cache. Chosen over SSE: plain JSON on the existing auth, middleware and cache, nothing streamed
through the gzip and Problem Details layers, and it works the same over MCP.
SAOS has no Supreme Court rulings after June 2016 (its newest SN judgment is III KK 195/16; common
courts are current). A judgment search, a court=SN filter or an SN case number ("III CZP 25/22",
"V KK 12/21" — citations.SN_REPERTORIA) carries a notice in notices[], in the API, the MCP output
and the console: "Orzeczenia Sądu Najwyższego po 2016 r. nie są dostępne w SAOS — szukaj na sn.pl",
linking https://www.sn.pl/orzecznictwo; an SN case number resolve cannot find gets the same notice
instead of a bare empty answer.
EUR-Lex reuse and attribution
Commission Decision 2011/833/EU allows commercial and non-commercial reuse of EUR-Lex content;
metadata is CC0 and consolidated texts are CC BY 4.0. Every EU item Insider returns carries
attribution: "© Unia Europejska, https://eur-lex.europa.eu/ — ponowne wykorzystanie zgodnie z
decyzją 2011/833/UE; metadane CC0, teksty skonsolidowane CC BY 4.0". The EUR-Lex SOAP service
(which needs registration) is not used.
Texts come from CELLAR's content negotiation, verified against the live service:
GET https://publications.europa.eu/resource/celex/{CELEX} with
Accept: application/xhtml+xml, text/html;q=0.9 and Accept-Language: pl (then en) answers
303 See Other to http://publications.europa.eu/resource/cellar/{id}/DOC_1 on the same host, which
answers the text as XHTML (newer acts, judgments) or HTML (older acts). Insider follows that redirect
only to publications.europa.eu and only over https (the http:// Location is upgraded) —
every other redirect target is refused.
Citations
GET /resolve?citation= (and the console's search box) recognise, deterministically:
Dz.U. 2024 poz. 1061, Dz. U. z 2024 r. poz. 1061, Dz.U. 2020 Nr 12 poz. 34, Dz.U.2024.1061,
M.P. …, DU/2024/1061; with t.j. Insider follows "Tekst jednolity dla aktu" / "Inf. o tekście
jednolitym" to the current consolidated text; CELEX (32016R0679), Regulation (EU) 2016/679,
Directive 2019/1937, dyrektywa 93/13/EWG; Polish case numbers (III CZP 12/23,
II SA/Wa 123/24, K 1/20 → SAOS caseNumber) and CJEU cases (C-311/18 → CELEX 62018CJ0311).
Full text and OCR
Text comes from the source's HTML, converted to sanitised plain text (raw HTML is never stored for
rendering). An act published only as PDF is queued (ocr_job) and answered with
text_status: pending plus the official PDF link; the worker (single-instance) then runs, page by
page, escalating on low confidence (OCR_MIN_CONFIDENCE):
- the PDF text layer (pypdfium2 — in the core image),
- PaddleOCR-VL — only when a GPU is present,
- PaddleOCR PP-OCRv5 + PP-StructureV3 on CPU,
- Tesseract (Polish).
OCR_ENGINE=auto|paddle_vl|paddle|tesseract|off. The OCR engines are optional: the core image
contains no Paddle and no GPU wheel. They live in backend/requirements-ocr.txt, are installed by
backend/Dockerfile.ocr, and run under the compose profile ocr
(docker compose --profile ocr up -d --build, with OCR_WORKER=external in .env). With OCR off
everything works: PDF-only acts get their text layer, or stay pending/failed with the PDF link.
All engines are Apache-2.0; Surya, MinerU, marker and PyMuPDF are excluded (the licence gate denies
them by name; CI's ocr-license job gates the OCR closure). A cloud vision fallback through the
platform's shared model providers is out of scope now — a documented seam in app/ocr/.
REST API
All under /api/v1, behind the app's auth (session cookie or Authorization: Bearer insider_pat_…,
plus the module permission guard); errors are application/problem+json.
| Route | |
|---|---|
GET /search — q, kind (all/act/judgment), jurisdiction (all/pl/eu), date_from, date_to, court (judgments only), case_number, citation, publisher (DU/MP/EU, acts only), in_force (acts only), cursor, limit (≤ 50), progressive |
federated search; answers carry sources, filter_scope, notices, pending |
GET /search/pending?ticket= |
the deferred slow source (SAOS) of a progressive search — a long poll |
GET /acts/{DU or MP}/{year}/{pos} and …/text?part=&max_chars= |
a Polish act; its text in chunks |
GET /acts/eu/{celex} and …/text |
an EU act |
GET /judgments/{saos or eurlex}/{id} and …/text |
a judgment (SAOS id or CELEX) |
GET /answer?q=&jurisdiction= |
a cited answer from retrieved passages, or a refusal — only with ai_answers on (see Models); 409 otherwise |
GET /resolve?citation= |
citation → documents (with t.j. resolution) |
GET /sources |
each source: on/off, circuit state, rate, capabilities, attribution |
GET /graph/article?act=&article= |
the reference graph: one article (structure path, cited by / references out) — INDEXED mode; 409 otherwise |
GET /graph/references?act=&article=&direction=&depth=&limit= |
its references in/out: type, detail (§/ust./pkt), the citing sentence |
GET /graph/path?from_act=&from_article=&to_act=&to_article=&directed= |
the shortest chain of references (≤ 6 hops) |
GET /graph/view?act=&article= |
nodes + edges for a drawing, ≤ 500 articles |
MCP
The official MCP Python SDK serves streamable HTTP at /mcp in the same process (stateless, JSON
responses). Tools: search_acts, search_judgments (both with jurisdiction: pl, eu or all),
get_act (ELI id, citation or CELEX), get_judgment (SAOS id, CELEX or C-311/18),
resolve_citation, and in INDEXED mode the reference graph's find_article,
article_references and trace_reference_path. At most 20 items per search, max_chars 20 000 by default, snippets ≤ 300
characters; every item has its official_url, source and attribution.
Authentication is a bearer app token (insider_pat_…): create one under Tokeny MCP in the
console (standalone; on the platform tokens are minted in Atrium). A read-only token is enough. The
module permission guard applies; an unauthenticated call, or a browser cookie alone, gets 401.
Claude Code:
claude mcp add --transport http insider http://localhost:8101/mcp --header "Authorization: Bearer insider_pat_..."
Claude Desktop (claude_desktop_config.json, through mcp-remote):
{ "mcpServers": { "insider": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:8101/mcp", "--header", "Authorization:${INSIDER_AUTH}"],
"env": { "INSIDER_AUTH": "Bearer insider_pat_..." } } } }
On the platform the URL is https://<platform>/insider/mcp.
Console
A search shows that it is running: the button is disabled, "Szukam…" is announced (aria-live),
the results region is aria-busy with skeleton rows, and the status line lists each source as
pending ("ELI…", "SAOS…", "Indeks…") until it answers with its latency. While SAOS is still pending,
the judgments group shows "Orzeczenia: ładowanie… (SAOS bywa wolny, do ~30 s)" with the seconds
elapsed. A newer search cancels the older one's indicator; "Więcej wyników" uses the same one.
PL-first (EN in i18n), on the family's ui/v1 shell (frontend/ui/v1/, a copy of Atrium's). One
search box that also takes citations (a recognised one jumps straight to the document), filter chips
(all/acts/rulings, PL/EU, dates, court, in force only), the per-source status line, results in
groups — acts first (Polish, then EU; an empty group says "Brak aktów pasujących do treści
zapytania"), judgments second — with a preview pane (metadata, cited provisions, text status, the start of the text, "Pełny
tekst", "Źródło", "Cytuj"), a document view with an outline (art. → ust. → pkt; sections of a ruling)
and paging, Źródła (read-only source status) and Tokeny MCP (create — the token is shown
once — revoke, and a ready MCP config).
Article aliases — resolve as one key lookup
In INDEXED mode (INSIDER_ARTICLE_ALIASES, on by default) a job keeps article_alias (alembic
0010), Elasticsearch-alias style: many keys, one target.
- Keys:
kc:483,DU/1964/93:483,DU/2026/795:483→ Art. 483 in the civil code's CURRENT consolidated text (integrations/codes.pyfor the abbreviation, the reference graph'sResolverfor which text is current);rodo:6,gdpr:6,dsa:34,ai-act:5,celex:32016R0679:6→ the article in the stored text of the act's newest consolidated version (integrations/eu_acts.py, a reviewed list — its docstring says how to add an entry);sig:III CZP 12/20(spaces, case, "3 CZP" → "III CZP" and "/" spacing folded),sig:C-311/18,ecli:ECLI:EU:C:2020:559→ EVERY judgment with that number, ranked court tier, then newest. SAOS publishes no ECLI, so Polish ECLIs have no key yet. - Rows carry
partandoffsetas/acts/{eli}/textcuts the stored text, and the article's text up to the next article (4 000 characters). One act's rows are swapped in ONE transaction, so a new t.j. re-points every key at once. - When:
INSIDER_ARTICLE_ALIASES_SCHEDULE(default 05:30) and after every dataset or graph sync. Incremental (a fingerprint per act group,updated_atfor SAOS); one act in hand at a time, judgments in keyset pages of 2 000. resolveasks the table first — one indexed query — and answersarticle.locate: "alias"; when the table is missing, empty, not built yet or lacks the key, it locates the article in the act's text (locate: "outline", LIVE's path) or searches SAOS / CELLAR for a case number (locate: "search"). The response has the same keys either way. Caveat: the aliaspartis computed on the locally stored text; an act whose/textis served from ELI's HTML instead may cut its parts differently.
Cited in case law — judgments citing articles (orzecznictwo)
services/caselaw.py runs the reference graph's own grammar and resolver over the SAOS judgments'
sections: "art. 415 k.c.", "art. 22 § 1 k.p.", "art. 361 § 1 i 2 Kodeksu cywilnego", "art. 5
ustawy z dnia … (Dz. U. … poz. …)", "art. 189 k.p.c. w zw. z art. 415 k.c." (kind W_ZWIAZKU_Z),
plus the judges' bare shorthand right after a citation ("kpc", "KC") and the EU acts' common names
("art. 6 ust. 1 lit. f RODO", eu_acts.py). Precision over recall: a citation naming no act, or an
act / article the box does not hold, is no row. Every row points at the CURRENT text's article (a
superseded t.j. is re-pointed after each pass). Rows live in case_ref (one per judgment and
article, court + date copied in) and case_ref_count (judgments, distinct courts, newest date per
article; alembic 0012) — never in legal_ref, so act-to-act PageRank stays a graph of acts.
indexing.CaseRefJob runs after saos_dump and the graph (INSIDER_CASE_REFS_SCHEDULE, default
45 5 * * *; INSIDER_CASE_REFS=false turns it off), incrementally by SAOS updated_at, reading
INSIDER_CASE_REFS_PAGE judgments at a time in keyset pages with short transactions; a stopped pass
resumes after its last page. Nothing in a request path reads the tables before its first complete
pass: GET /api/v1/graph/case-law and the MCP tool article_case_law answer ready: false,
find_article / resolve say cited_in_case_law: null, and the /graph article panel says
"Orzecznictwo jeszcze się buduje". Once ready the panel lists "Orzecznictwo (N)" (court tier first,
newest first, linking to the judgment) and /graph/top has a "w orzecznictwie" column.
INSIDER_CASE_LAW_PRIOR (default 0, off) multiplies an article's search score by
(1 + w·ln(1 + judgments)); tests/search_eval.py --profile=all showed no difference with it on
(INSIDER_EVAL_CASE_LAW_PRIOR=0.1), so it stays off.
Reference graph — which article cites which
In INDEXED mode (INSIDER_LEGAL_GRAPH, on by default) a job parses every searched act's articles
for citations of other articles — "art. 535", "art. 42¹ § 3", "art. 10 ust. 2 pkt 3", lists and
ranges ("art. 5–7", "art. 1, 3 i 5"), "tego kodeksu" / "niniejszej ustawy" (the act itself), and
other acts by Dz.U. citation, code name or abbreviation ("Kodeksu postępowania cywilnego", "k.c.")
or dated name ("ustawy z dnia 10 maja 2018 r. o ochronie danych osobowych") — with a lark
grammar (backend/app/services/legalref.lark). A citation of an act the index holds resolves to
that act's CURRENT text; any other keeps its name, unresolved. Each reference is typed
(ODSYLA_DO, STOSUJE_ODPOWIEDNIO, Z_ZASTRZEZENIEM) and keeps its offset, so the citing
sentence is read back from the article. Ideas and fixtures from
tobayah/legal-memory (Apache-2.0, CREDITS.md).
- Storage: Postgres only —
legal_ref(one row per reference),legal_ref_count(cited by / references out per article, one GROUP BY after each build) anddzu_article.path(Księga › Tytuł › Dział › Rozdział › Oddział), alembic0008. No graph database. - When:
INSIDER_LEGAL_GRAPH_SCHEDULE(default 05:00) and after everydzu_md/eli_inforcesync, never beforedzu_md's first full pass. Incremental: only acts whose text changed are re-parsed, one at a time (memory stays flat); references into a text a newer t.j. superseded are re-pointed. The first build parses everything (~4–5 ms per article locally). - Questions:
find_article,references(in/out, ≤ 3 hops, ≤ 200 edges each way),trace_path(a recursive CTE, breadth first, ≤ 6 hops and 20 000 walk rows; directed by default). - Search: every act-article hit carries
cited_by/refs_out("cytowany przez N / odwołania M" in the console). Ranking: see "Ranking" below —tests/search_eval.pybuilds the graph too (--no-graphfor the table without it; both states are asserted). - Ranking (
services/rank.py,services/pagerank.py; every search answersrank_prior):- naive — always, LIVE and INDEXED, metadata only: a code and the consolidated text up; an
amending act ("o zmianie"), a notice that is not a t.j., a one-off act and a repealed act down
(
dzu_md.act_prior); ×3 for the act the query NAMES ("Kodeks cywilny", "k.c.", "KC", "kodeksu cywilnego", an act's full name) and ×0.5 for every other act then. A code's abbreviation searches as its name; ELI's title search asks for the code's name exactly. - graph — PageRank (damping
INSIDER_LEGAL_RANK_DAMPING0.85, weighted by confidence, numpy power iteration, ≈40 MB at 1.5× the box's graph) computed after every FINISHED graph build intolegal_act_rank/legal_article_rank(alembic0009). Used only when that pass is on the graph's latest finished build and coversINSIDER_LEGAL_RANK_MIN_COVERAGEof its sources (two O(1) state reads); otherwise the naive prior answers alone. It REPLACES the in-degree count prior (in-degree is PageRank's first-order term — stacking both counts each citation twice): a part ×1 + INSIDER_LEGAL_GRAPH_PRIOR × ln(1 + its PageRank), a live act hit ×1 + INSIDER_LEGAL_RANK_ACT_PRIOR × ln(1 + its act PageRank). - what the act is, by its name — on a full-text query that names no act, graph or no graph:
× up to
INSIDER_RANK_TITLE_MATCH(1.5) for the query's words in the act's name, each word weighted by its rarity among the stored acts' names ("ochrona konsumenta": ustawa o ochronie konkurencji i konsumentów over k.p.c., which only has the consumer court's procedure), and ×INSIDER_RANK_SPECIAL_ACT(0.5) for an act "o szczególnych rozwiązaniach …" — temporary exceptions (the COVID-19 act's art. 31u over k.c. art. 673 for "wypowiedzenie umowy najmu"). Article PageRank cannot do this: on the box k.c. art. 415 has no resolved citation at all. - which articles stand for an act — those opening a unit whose HEADING holds the query's
words (or a thesaurus variant's) first (
INSIDER_RANK_HEAD_FIRST): the drafters' label of the subject, the general rule before the special ones (art. 415 under "Czyny niedozwolone" before the product liability of art. 449¹⁰). It never changes the act's rank.
- naive — always, LIVE and INDEXED, metadata only: a code and the consolidated text up; an
amending act ("o zmianie"), a notice that is not a t.j., a one-off act and a repealed act down
(
- The pages
/graph/(article neighbourhood: depth, direction, edge types),/graph/act(one act's structure and internal references) and/graph/path(the chain between two articles): Jinja2 templates (autoescaped) with htmx partials (expand, filter, the article side panel, the path search) and Cytoscape.js drawing what Python sends — never more than 500 articles, concentric for an act, breadthfirst around an article. Same session and module permission as the API (every route depends onget_current_user), GET only, and the console's CSP unchanged: same-origin scripts only (frontend/vendor/,frontend/graph.js), no inline handlers, htmx withallowEval: false. The console's results link to them.
Stack
FastAPI + SQLAlchemy 2 + Alembic + PostgreSQL 16 / 17, Argon2id password hashing, server-side cookie sessions, an append-only audit log enforced by database grants, RFC 9457 Problem Details errors, opt-in OpenTelemetry, and a no-build vanilla-JS console (Open Color palette, Tabler icons, light/dark theme, two languages). Shipped with Docker Compose; the backend is its own edge (no reverse proxy). Apache-2.0, and CI refuses any GPL/AGPL/SSPL dependency.
dredd-core
Identity and sessions, authentication, the access-control resolver, the org tree, the audit
writer, the security primitives, the shared enums and error types, and the engine/session
factories all come from one installed package. backend/requirements.txt pins it by tag:
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.17.0
The app-side files that used to hold that code (services/auth.py, models/__init__.py,
security.py, errors.py, … and, in nodes tenancy, services/authz.py) are now thin shims:
they re-export from dredd_core so every call site keeps its import path, and they hold only what
is genuinely this app's — the insider_pat_ token prefix, the insider_session cookie,
the settings fed into core's auth policy. Fixing shared behaviour means changing dredd-core, tagging
a release and moving the pin here — never patching a shim.
dredd-core ships models, not migrations: importing it registers its tables on the shared
metadata, and this repo owns its own 0001 (native enum types are created first, then
create_all). A core upgrade that changes the schema needs a new revision here.
It is a private repository. Local installs use your own GitHub credentials; CI authenticates
with a DREDD_CORE_TOKEN repository secret (a fine-grained PAT with read access to
Alpaq92/dredd-core), which the workflow injects before pip install. Without it, the install
step fails with an authentication error.
This app is its own deployment with its own domain data. It shares code with its siblings, not that data: locally it has its own database; in the family's shared managed database it has its own schema and roles, which no sibling's roles can reach.
Identity is the exception, and it is shared on purpose: the family's shape is one platform, one
account, one admin pane — one origin, one module per path, where you sign in once at the hub and
every module resolves the same session. Separate schemas, one roster. As scaffolded this app is
standalone: it serves at the root of its own host with its own accounts, its own sign-in and its
own Users administration, and it keeps running that way whatever the family does. Mounting it under
a path prefix of a shared origin is one setting (ROOT_PATH, empty by default) and no code change.
Joining the platform
Sharing the roster is one more setting, IDENTITY_SCHEMA, plus three steps that are not this app's
to take. Once it is set, app_user, session and module_permission live in a neutral schema the
hub owns and this app reads: there is no password here, the sign-in screen becomes a link to the
hub, creating or re-passwording an account answers 409 pointing there, and app tokens stay listable
and revocable but are minted at the hub. And module_permission is what decides who may open this
app at all — no row for this module is no entry — so the hub is where somebody is admitted to it
and where somebody is made its moderator. Standalone that table is inert: there is one application,
and having an account here is permission to use it. One origin means one cookie, so there is no handoff to
build — no signed assertion, no audience binding, nothing to exchange. A design that adds one for
this topology is over-engineering.
Both shapes are the same code, switched at runtime, and that is the property to defend: the moment they fork, the shape nobody runs locally is the shape that breaks.
The order matters, because only the last of the four steps happens in this repository:
- The platform admin provisions.
db/managed/provision.sql, re-rendered with--identity-schema/--identity-owner: the schema,USAGEfor this app's two roles, and asearch_paththat reaches it. A migrator role may do none of those. - The hub migrates. It owns the schema, so it creates the three tables and grants this app's
roles their tier — a column-restricted
SELECTonapp_userthat does not includepassword_hash,SELECTplus a narrowUPDATEonsession,SELECTand nothing else onmodule_permission, andINSERTon none of them. - A person imports any account this app has and the hub does not. Neither side can do it alone,
by design, so it is a platform-admin step run from a census of every schema's
app_user. alembic upgrade headhere runs0003_shared_identity: it matches this schema's accounts to the shared ones by e-mail address, rewrites every id that names a person, re-points every foreign key, and drops the local copies. Read it before running it on anything you care about. Sessions and app tokens are deliberately not carried over — everybody signs in once more, at the hub.
Two administration tiers come with it, and these are the only two words for them: an administrator is platform-wide and is made in the hub; a moderator administers this module only, is also made in the hub, and is merely read here. Standalone they are the same thing and nothing queries anything.
Quick start
cp .env.example .env # then set the three DB passwords
DREDD_CORE_TOKEN=github_pat_... docker compose up -d --build # postgres -> migrate(+seed) -> backend
Building the image needs
DREDD_CORE_TOKEN(a read-only fine-grained PAT forAlpaq92/dredd-core) in your shell — compose hands it to the build as a BuildKit secret, so it never lands in an image layer. Don't put it in.env: every container loads that file at runtime. CI'scompose-smokejob runs exactly this stack on every push.
Open http://localhost:8101 and sign in with BOOTSTRAP_ADMIN_EMAIL / BOOTSTRAP_ADMIN_PASSWORD.
Windows: write
.envwithout a BOM —[System.IO.File]::WriteAllText("$PWD\.env", (Get-Content .env.example -Raw)). PowerShell'sOut-File -Encoding utf8adds one, and pydantic-settings folds it into the first key name, which produces a baffling "field required" error at startup.
Development
cd backend
python -m venv .venv && . .venv/Scripts/activate # or: source .venv/bin/activate
pip install -r requirements-dev.txt # pulls dredd-core from GitHub — needs repo access
pytest # DB-free unit tests
alembic upgrade head --sql # inspect the DDL without a database
python scripts/license_gate.py # no GPL/AGPL/SSPL
python scripts/deploy_check.py # stack-definition coherence
node --check ../frontend/app.js # the console has no build step, so this is the check
The API is served under /api/v1, with OpenAPI docs at /api/v1/docs.
Testing with and without local infrastructure
Insider answers LIVE by default and leans on whatever local infrastructure the box has — the
tantivy index, the sjp.pl lexicon, the reference graph, its PageRank, the vectors, the CELLAR
tables — each of which can be absent, half-built or stale. tests/infra.py names those states of
the whole box as profiles, built cheaply from the committed search fixture and the fake
upstreams (tmp dirs, never a network):
| profile | index | lexicon | graph | rank | vectors | CELLAR | live upstreams | aliases |
|---|---|---|---|---|---|---|---|---|
bare |
— (LIVE only) | no | — | — | — | empty | up | — |
fresh |
INDEXED on, nothing built | yes | — | — | — | empty | up | table empty |
index_only |
format 3 | no (plstem) | — | — | — | empty | up | — (before 0010) |
index_graph |
format 3 | yes | complete | — | — | empty | up | — (before 0010) |
full |
format 3 | yes | complete | complete | complete | complete | up | complete |
graph_partial |
format 3 | yes | interrupted | stale | complete | partial | up | complete |
vectors_partial |
format 3 | yes | complete | complete | no last_pass |
complete | up | complete |
rebuild_pending |
format 2 serving | yes | complete | complete | complete | complete | up | complete |
upstream_down |
format 3 | yes | complete | complete | complete | complete | 503 | complete |
upstream_timeout |
— | no | — | — | — | empty | hanging | — |
graph_no_aliases |
format 3 | yes | complete | complete | complete | complete | up | table empty |
aliases_partial |
format 3 | yes | complete | complete | complete | complete | up | acts only |
A test asks for the infra fixture and runs once per profile; @pytest.mark.infra("bare", "full") narrows it. tests/test_infra_matrix.py holds the invariants every profile keeps: one
response shape, the Civil Code's t.j. first for "Kodeks cywilny" / "k.c.", rank_prior = "graph"
only with a complete rank, the vector side only with complete vectors, an index_* notice exactly
when a local source cannot serve, nothing built / downloaded / loaded in the request path, every
CELEX returned opens, charset=utf-8, and a memory ceiling per request. tests/test_aliases.py
runs every resolve behaviour in bare, index_only, graph_no_aliases, aliases_partial and
full.
pytest tests/test_infra_matrix.py # every profile, DB-free
pytest tests/test_infra_matrix.py --infra=bare # one profile (or INSIDER_INFRA=bare,full)
python tests/search_eval.py --profile=all # the top-3 table per profile (or --profile full)
INSIDER_RUN_INTEGRATION=1 INSIDER_INFRA_DB=1 pytest tests/test_infra_matrix.py --infra=full
# the profile's state in Postgres: a THROWAWAY
# database only (it refuses one holding acts)
Every new feature that depends on local infrastructure is tested in bare and full (CI's
infra-matrix job runs both, DB-free and on Postgres) — and in the degraded profile its component
can be in, when it has one.
Deploying on a managed PostgreSQL
The Dredd family can run in one shared managed database (one PostgreSQL 16/17 database at a managed
provider), with Atrium as the hub; Insider joins it as schema insider with its own roles
insider_migrator and insider_app. The provider hosts only the database — the backend still
runs on your server, with docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build. The same path works against any PostgreSQL 16/17 whose admin may create roles and schemas.
- Database-wide steps (creating the database, the provider's root CA, keeping the schemas out of
any auto-generated API, TLS enforcement, network restrictions, the connection budget, backups and
point-in-time restore): step 0 of
db/managed/README.md, and in more depth the family runbook in Atrium,deploy/README.md. - Insider's steps (provisioning with
python -m dredd_core.managed provisionor the rendereddb/managed/provision.sql,.envwithDB_APP_ROLEand the pool knobs, migrate + seed,python -m dredd_core.managed check, restore specifics):db/managed/README.md. - Connect through the provider's pooler in session mode (never a transaction-mode port such as
6543) or directly, as
<role>— or<role>.<tenant>where the pooler wants the tenant in the user name — with?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt. Never migrate aspostgres. - The TLS rule: a database host that is not local (
"",localhost,127.0.0.1,::1,postgresor aDB_LOCAL_HOSTSentry) must carrysslmode=verify-full, or the app refuses to start.
CI's managed-db job rehearses this path on PostgreSQL 17 without a superuser: it emulates a managed
Postgres (python -m dredd_core.managed emulate), provisions the app next to a sibling, migrates, runs
the integration suite as insider_app and runs the managed check.
Security model
Two Postgres roles do the heavy lifting. migrator owns DDL and is used only by Alembic; app
is the runtime role and holds DML only. The migration then revokes UPDATE/DELETE on
audit_log from app, which is what makes the audit log evidence rather than a convenience: a
compromised application cannot rewrite its own history, because the database will not let it.
The runtime role's name is configuration (DB_APP_ROLE, app by default): the grants migration
(0002_runtime_grants) grants to it and fails loudly — rolling back — when that role is missing,
when it runs as a superuser or the platform admin, or when a grant did not take. Migrations run as the
migrator and nothing else.
Only the backend is published to the host (:8101, the family's standalone scheme: Galena 8021, Sygna 8041, Compass 8061, Counsel 8081, Insider 8101; on the platform the modules publish nothing) — it serves the console and sets every security
header itself (backend/app/edge.py); Postgres is expose-only. There is no reverse proxy.
Access control lives in exactly one module, backend/app/services/authz.py — a re-export of
dredd_core.authz in nodes tenancy, a local admin/owner check in simple tenancy. No access
returns 404, not 403: a 403 confirms that the record the caller may not see exists.
Project layout
| Path | What |
|---|---|
backend/app/integrations/ |
the source adapters (ELI, SAOS, EUR-Lex) and SourceClient (fixed hosts, politeness, circuit breaker) |
backend/app/services/legal.py |
the facade REST and MCP share; federation, cursor, citations, cache, doctext, htmltext beside it |
backend/app/ai/ |
the model interfaces (Embedder, Reranker, Generator), the registry, local ONNX + HTTP backends; services/semantic.py + vectorindex.py use them |
backend/app/ocr/ |
OCR tiers, per-page escalation, the queue worker |
backend/app/mcp_server.py |
the MCP tools and the /mcp endpoint (bearer app token + module guard) |
backend/app/models/ |
legal.py: source_cache, doc_text, ocr_job; __init__.py re-exports dredd-core's |
backend/app/services/ |
every domain rule and all SQL; auth/audit are core shims (authz too, in nodes tenancy) |
backend/app/routers/ |
HTTP shape, validation, authz calls — no SQL |
backend/alembic/ |
0001: enum types → create_all; 0002: runtime grants; 0003/0004: identity; 0005: Insider's tables (idempotent) |
backend/scripts/ |
license gate, deploy pre-flight |
frontend/ |
the console: index.html + app.css + app.js on ui/v1/, no bundler |
db/init/ |
least-privilege role creation for the local stack, run once by Postgres |
db/managed/ |
the shared managed database: rendered provision.sql + this app's runbook |
docker-compose.managed-db.yml |
override for a managed database: no local postgres, CA mounted, no migrator in the backend |
License
Apache-2.0. See CREDITS.md for dependencies and design credits.