adminandClaude Opus 5.5 bf4860a9c4 Search quality: one answer per act, better ranking, eli_inforce resumes
- One act, one answer: every consolidated text since 2012 is grouped by
  the act's name and only the newest stays searchable (reconciled after
  every dzu_md / eli_inforce run and before every rebuild); the adapter and
  federation also drop repeats.
- Ranking (index format 2): the title is the act's name, not the notice
  text; chapter headings and each article's first sentence are fields of
  their own; phrase and proximity boosts (function words kept for the exact
  phrase); a prior for codes over amending acts, notices and repealed acts.
  Offline evaluation on 17 real acts: 11 of 11 target queries pass (3
  before), e.g. "umowa o prace" -> Kodeks pracy, "zachowek" -> KC art. 991.
- An interrupted dzu_md / eli_inforce run resumes after 10 minutes instead
  of 24 h; eli_inforce follows dzu_md's first full pass.
- FORMAT recorded per index: a mismatch rebuilds from Postgres.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 14:27:21 +02:00

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

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 stemmed in Python by the in-house plstem (folded diacritics, one ending off; a query word with a mobile e also matches its e-less form: najem ↔ najmu), 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 every INSIDER_DZU_MD_SYNC_INTERVAL_HOURS (6): 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 only in the off-peak UTC window INSIDER_SAOS_DUMP_WINDOW (23:00–05:00), 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 weekly (acts it no longer lists are marked out of force — kept, never searched), a delta 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

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 carries extra.disclaimer "nieoficjalna konwersja; tekstem wiążącym jest PDF w Dzienniku Ustaw", source_pdf (the binding PDF), eli_url and dataset_url.
  • Judgments: saos_index stands 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: cellar stands in for live CELLAR's title search for the kinds it holds ready and fresh (INSIDER_CELLAR_STALE_HOURS) — acts, and judgments when cellar_caselaw is 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, an in_force=false filter and a stale index go live as before. The SPARQL shapes and the HTML structure pass are vendored from tseidl/eurlex-builder (MIT) into app/integrations/cellar_builder/ and adapted (Polish headings, the in-force filter, keyset paging, the delta, stdlib parsing through SourceClient) — 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, and running | 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.

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):

  1. the PDF text layer (pypdfium2 — in the core image),
  2. PaddleOCR-VL — only when a GPU is present,
  3. PaddleOCR PP-OCRv5 + PP-StructureV3 on CPU,
  4. 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 /resolve?citation= citation → documents (with t.j. resolution)
GET /sources each source: on/off, circuit state, rate, capabilities, attribution

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. 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).

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.15.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:

  1. The platform admin provisions. db/managed/provision.sql, re-rendered with --identity-schema / --identity-owner: the schema, USAGE for this app's two roles, and a search_path that reaches it. A migrator role may do none of those.
  2. The hub migrates. It owns the schema, so it creates the three tables and grants this app's roles their tier — a column-restricted SELECT on app_user that does not include password_hash, SELECT plus a narrow UPDATE on session, SELECT and nothing else on module_permission, and INSERT on none of them.
  3. 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.
  4. alembic upgrade head here runs 0003_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 for Alpaq92/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's compose-smoke job runs exactly this stack on every push.

Open http://localhost:8101 and sign in with BOOTSTRAP_ADMIN_EMAIL / BOOTSTRAP_ADMIN_PASSWORD.

Windows: write .env without a BOM — [System.IO.File]::WriteAllText("$PWD\.env", (Get-Content .env.example -Raw)). PowerShell's Out-File -Encoding utf8 adds 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.

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 provision or the rendered db/managed/provision.sql, .env with DB_APP_ROLE and 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 as postgres.
  • The TLS rule: a database host that is not local ("", localhost, 127.0.0.1, ::1, postgres or a DB_LOCAL_HOSTS entry) must carry sslmode=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/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.

S
Description
No description provided
Readme Apache-2.0
2.9 MiB
Languages
Python 85.9%
JavaScript 8.5%
CSS 3%
HTML 1.3%
PLpgSQL 1%
Other 0.2%