- 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>
48 KiB
CLAUDE.md
Guidance for Claude Code when working in this repository.
What this is
Insider — Polish and EU legal acts and case law, searched and fetched live at the official
sources (Sejm ELI API, SAOS, EUR-Lex/CELLAR) over REST (/api/v1), MCP (/mcp) and a console. See
"Insider's domain" below for the rules specific to it. Built on dredd-core, the shared substrate of this app family:
identity, sessions, auth, the access-control resolver, the org tree, audit and the security
primitives are an installed dependency, not source in this repo. Stack: **FastAPI + SQLAlchemy 2
- Alembic + PostgreSQL 16 / 17**, Argon2id auth + server-side cookie sessions, a
no-build static console (vanilla JS), Docker Compose, with the backend as its own edge (
app/edge.py, no reverse proxy). License Apache-2.0; every dependency is permissive (no copyleft).
The core is pinned by tag in backend/requirements.txt:
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.17.0
It is a private repository, so installing it needs a token — see README.md for the
DREDD_CORE_TOKEN secret CI uses. Upgrading core means moving that tag deliberately: read the
core changelog, bump the pin, run the tests.
This app is its own deployment with its own data. It shares code with its siblings, not
domain data — locally its own database, in the family's shared managed database its own schema
insider and roles that no sibling's roles can reach. That isolation stays.
Identity is the exception, and it is one setting. The family's shape is one platform, one account, one admin pane: one origin, one module per path, where a person signs in once at the hub and every module resolves the same session — separate schemas, one roster. "Separate databases" never meant "separate logins"; don't write that it did, and don't design a cross-origin token handoff for a topology that has one origin.
IDENTITY_SCHEMA is the whole switch, and it is empty here, which is STANDALONE: this app owns
app_user / session / module_permission in its own schema, has its own sign-in screen and its own
Users administration. That must keep working for ever — an app with its own database and its own
people is a supported deployment, not a stage to grow out of. Set it and this app becomes a MODULE:
those three tables live in a neutral schema the hub owns and this app READS, the sign-in form becomes
a link to the hub, account writes answer 409, and app tokens stay listable and revocable but are
minted there. Both shapes are one code path, switched at runtime — never two, or the one nobody
runs locally is the one that breaks. alembic/versions/0003_shared_identity.py is the cutover and
.env.example has the order the steps go in; ROOT_PATH (also empty here) is the separate switch
that mounts this app under a path prefix.
Terminology, exactly these three words: "administrator" = platform-wide, "moderator" = this
module only, "user" = may open this module and nothing more. A module guards its own
administration with deps.require_moderator and defines no administrator-only guard at all —
every power left in a module is module-scoped, so a route here held to the platform-wide tier would
only lock a moderator out of the job they were given. Whether somebody may be here at all is asked
once, in deps.get_current_user.
Where things live
dredd-core (installed) Base · NAMING_CONVENTION · UUIDPkMixin · TimestampMixin · SafeInet · pg_enum
AppUser · Session · AppSetting · AuditLog · Node · PermissionGrant · Favorite
dredd_core.enums NodeRole PrincipalType ReviewPolicy EncryptionMode
SessionKind TokenScope
dredd_core.errors AppError AuthenticationError AuthorizationError
NotFoundError ConflictError ValidationError
dredd_core.security hash_password verify_password generate_session_token
hash_token derive_key generate_app_token
token_display_prefix
dredd_core.audit record
dredd_core.authz effective_role assert_can_read assert_role
users_with_role_at_least find_user_grant
upsert_user_grant remove_user_grant
list_grants_for_display grants_for_user
access_state ancestor_paths ancestor_or_self_nodes
readable_node_ids register_overlay clear_overlays
dredd_core.auth AuthPolicy · AuthService
dredd_core.db make_engine (TLS URL params) · make_session_factory
strip_tls_params
dredd_core.schema create_enum_types · runtime_grants_sql
dredd_core.managed provision · check · emulate (TEST-ONLY) (python -m)
backend/app/
main.py config.py db.py deps.py errors.py security.py enums.py schemas.py seed.py
observability.py logging_config.py (db/errors/security/enums are shims)
models/ __init__ (shim: re-exports core's AppUser/Session/ModulePermission/AppSetting/AuditLog
[+ Node/PermissionGrant/Favorite in nodes tenancy])
legal (source_cache · doc_text · ocr_job — Insider's own tables)
services/ auth · audit · moderation (shims over dredd_core)
authz (nodes tenancy: shim over dredd_core.authz · simple: local moderator/owner rules)
changes · settings · nodes · audit_log · legal & co. (this app's logic, see below)
(nodes: nodes tenancy only · audit_log: the read-only audit query)
routers/ health auth users admin legal (+ /mcp, app/mcp_server.py)
backend/tests/ unit (DB-free, always run) + integration (opt-in)
backend/alembic/ env + 0001_initial (pgcrypto, create_enum_types, create_all)
+ 0002_runtime_grants (runtime_grants_sql for DB_APP_ROLE; evidence tables in models/__init__)
+ 0003_shared_identity (the cutover: merge this schema's accounts into the
platform's, re-point every foreign key, drop the local copies — a NO-OP unless
IDENTITY_SCHEMA is set, and refused on downgrade when it is)
+ 0004_module_permission (dredd-core v0.11.0 renamed `module_moderator`; a database
whose 0001 ran before that still has the old table, and 0001 never runs again —
rename it, add `role`, or build it from the metadata, decided by the catalog)
+ 0005_insider_domain (source_cache, doc_text, ocr_job IF NOT EXISTS; drops the
scaffold's `record`; re-runs the runtime grants)
+ 0006_indexed_mode (dzu_act, dzu_article, saos_judgment, saos_section,
dataset_sync IF NOT EXISTS; re-runs the runtime grants)
+ 0007_cellar_index (eu_doc, eu_part IF NOT EXISTS; drops the retired
`eurlex_dump` state row; re-runs the runtime grants)
+ 0008_legal_graph (legal_ref, legal_ref_count IF NOT EXISTS; dzu_article.path
ADD COLUMN IF NOT EXISTS; re-runs the runtime grants)
+ 0012_case_refs (case_ref, case_ref_count IF NOT EXISTS — judgments citing
articles, `services/caselaw.py`; re-runs the runtime grants)
backend/scripts/ license_gate · deploy_check
frontend/ index.html · app.css · app.js · ui/v1/ (the family shell) (no build step)
Tabler icon path data vendored into app.js's ICN map (CREDITS.md)
db/init/ 01-roles.sh (creates the app + migrator roles — local stack only)
db/managed/ provision.sql (rendered by dredd-core; CI checks it) · README.md (managed-database runbook)
docker-compose.yml · docker-compose.managed-db.yml · .env.example · .github/workflows/ci.yml
Strict one-way layering — routers/ (HTTP, validation, authz; never touches SQL) →
services/ (domain logic) → models/ (ORM). Keep it.
Commands
DREDD_CORE_TOKEN=... docker compose up -d --build # full stack; the token is a BuildKit build secret —
# shell only, never .env (containers load .env)
cd backend && pytest # DB-free unit tests; integration auto-skips
INSIDER_RUN_INTEGRATION=1 pytest # full API loop (needs a migrated+seeded Postgres)
pytest tests/test_infra_matrix.py --infra=bare,full # the infra profiles (tests/infra.py); default all
python tests/search_eval.py --profile=all # top-3 table per infra profile
INSIDER_RUN_INTEGRATION=1 INSIDER_INFRA_DB=1 pytest tests/test_infra_matrix.py # profile state in
# Postgres — a THROWAWAY database only (refuses one with acts)
alembic upgrade head --sql # inspect the DDL with no database
python -m dredd_core.managed provision --sql-only --schema insider --app-role insider_app \
--migrator-role insider_migrator --check-file ../db/managed/provision.sql # rendering current?
python scripts/license_gate.py # CI license gate locally
python scripts/deploy_check.py # compose/Dockerfile/.env coherence
node --check frontend/app.js # ALWAYS after editing the console
Insider's domain — where it lives
backend/app/
integrations/ base (SourceAdapter, LegalDoc, Query, errors) · http (SourceClient: fixed host, no
cross-host redirects, trust_env=False, bucket, semaphore, retry, breaker, UA)
· politeness (TokenBucket, CircuitBreaker) · eli · saos · eurlex · registry
· local (LocalAdapter: INDEXED sources, no client) · dzu_md (mirror parsers,
upstream, adapter) · saos_dump (DUMP upstream + SaosIndexAdapter)
· cellar (CELLAR listing rows, records, CellarUpstream, CellarIndexAdapter)
· cellar_builder/ (VENDORED from tseidl/eurlex-builder, MIT: queries, structure)
services/ legal (THE facade REST + MCP call) · federation (fan-out, statuses, dedup)
· cursor (HMAC) · citations (regexes) · cache (LRU + source_cache, single-flight)
· doctext (doc_text + ocr_job queue) · htmltext (sanitise, chunk) · runtime (singleton)
· indexing (importers: dzu_md, eli_inforce, saos_dump, cellar ×2; run_loop)
· indexstore (Pg + Memory; run lock) · textindex (tantivy) · window (a daily window) · schedule (cron)
· legalref (+ legalref.lark, the citation grammar) · legalgraph (resolver, build,
find / references / trace / view); indexing.GraphJob builds it
· aliases (article_alias: kc:483 / rodo:6 / sig:… → one lookup per resolve);
indexing.AliasJob builds it
routers/graph.py + templates/graph/ the /graph pages (Jinja2 + htmx partials); the browser side
is frontend/graph.js(+css) over frontend/vendor/ (htmx 2.0.4, Cytoscape.js 3.30.4)
ocr/ engines (text layer, PaddleOCR, PaddleOCR-VL, Tesseract — import-guarded)
· pipeline (tier selection, per-page escalation) · worker (queue; in-process or
`python -m app.ocr.worker`)
mcp_server.py MCPServer (mcp 2.x) tools + the /mcp ASGI endpoint (bearer app token + module guard)
routers/legal.py /search /acts/... /judgments/... /resolve /sources /sources/datasets
models/legal.py source_cache · doc_text · ocr_job (alembic 0005, idempotent)
models/index.py dzu_act · dzu_article · saos_judgment · saos_section · dataset_sync (0006)
· eu_doc · eu_part (0007)
backend/requirements-ocr.txt + Dockerfile.ocr the OPTIONAL OCR image (compose profile `ocr`)
frontend/ui/v1/ the family's shared shell (a copy of Atrium's; don't edit locally)
Insider's domain — invariants
-
LIVE by default; INDEXED only from the scheduled importers. With
INSIDER_INDEX_ENABLED=false(the default) there is no copy of the sources: only the TTL cache of what people fetched, anddoc_text(sanitised ACT texts); nothing fills either ahead of a request. INDEXED mode (README) adds local datasets (models/index.py) and tantivy indexes underINSIDER_INDEX_DIR, filled ONLY byservices/indexing.py's importers (lifespan tasks that wait first, each behind its own switch and a per-dataset Postgres advisory lock — the two act datasets share one, they write one index). No route starts an import and no search waits for one. Never fill the cache ordoc_textfrom an importer, and never let a search reach a dataset host. -
An index answers only when READY and FRESH, and says so. A
LocalAdapterreportsskippedwith the reason (not built, first import unfinished, stale) and the live source answers as before; every status line carriesserved_byand the local onesfreshness.dzu_mdstands BESIDE ELI (its hits first, ELI's after);saos_indexstands IN for live SAOS only when it covers the whole query (covers()). Every mirror result carries the disclaimer "nieoficjalna konwersja; tekstem wiążącym jest PDF w Dzienniku Ustaw",source_pdf,eli_url; ELI stays authoritative for status and the current t.j. Old consolidated texts are flaggedsupersededand never searched — don't index them back. One act = one answer:indexing.reconcile_superseded(after every import of either act dataset and before an index rebuild) groups every text by its NAME (dzu_md.act_key: a t.j.'s notice, the act as published and ELI's title of it meet) and keeps only the newest by Dz.U. year/position searchable — the dataset holds every t.j. since 2012, and before this a search listed one act three times. Amending acts and non-t.j. notices are never grouped. The adapter andfederation.deduphold the same line (a live ELI act whose name an indexed answer already claimed is dropped). Articles are keyed by POSITION (numbers repeat). tantivy is pinned exactly inrequirements.txt(MIT) and import-guarded. -
EU law in INDEXED mode comes from CELLAR, anonymously (
cellar/cellar_caselaw, owner- approved 2026-10-21; it replaced the EUR-Lex dump seam, which needed an EU Login account). The importer uses ONLY the two channels the live adapter uses — SPARQL and the 303 text fetch, on aSourceClientof its own based atpublications.europa.eu, redirects allowlisted to that host (CellarUpstreamrefuses any other base) — one request in flight atINSIDER_CELLAR_RATE≤ 2 (every hop counted). Acts IN FORCE only, keyed by the BASE CELEX, holding the text of the NEWEST consolidated version (text_celex); Polish, else English withlanguagerecorded. A full pass weekly marks the acts it no longer listsin_force=false(tagnf: kept, never searched); daily passes are deltas oncmr:lastModificationDate.CellarIndexAdapter.replaces = "eurlex"PER KIND (covered_kinds,federation.plannarrows live CELLAR to the kinds left), so case law off never hides CJEU judgments. A CELEX / case-number lookup stays live. Every item keeps the EUR-LexATTRIBUTION,TEXT_NOTEand the official link; ids stayeurlex:<CELEX>. Tables of its own (eu_doc/eu_part), notdzu_act: an EU act must never be served beside ELI.cellar_builder/is VENDORED (MIT header kept, CREDITS.md): adapt it there, never add eurlex-builder as a dependency (duckdb/polars/pyarrow/requests, and its HTTP would bypassSourceClient). -
SAOS: two channels, never mixed. (1) The LIVE search API (
/api/search/..., robots.txt disallows/api/for crawlers): user-initiated queries only — one request at a time, ≤ 2 req/s (default 1), no retry of a slow query, identifying User-Agent, behindINSIDER_SOURCE_SAOS; never from a loop, a scheduler, the OCR worker or an ingestor, and its texts never go todoc_text. (2) The DUMP API (/api/dump/judgments), which SAOS's documentation offers for bulk download and the owner has approved (2026-10-21) for a local judgment index: ONLY that endpoint, only from the scheduled ingestor, incrementally (sinceModificationDate), politely (low rate, identifying User-Agent, off-peak), its rows stored in the index's own tables — not indoc_textor the cache. A live search never falls back to the dump endpoint, and the ingestor never calls the search API. In code:saos_dump.SaosDumpUpstreamrefuses a client not based at/api/dump/,parse_pagerefuses anextlink elsewhere, andSaosIndexAdapterhas no HTTP client at all (tests/test_indexed.pyasserts both directions). -
Fixed hosts. Base URLs are constants in
integrations/*.py, never settings or input; ids are validated and path-escaped;SourceClientrefuses a cross-host redirect and ignores environment proxies. SPARQL takes user text only througheurlex._literal(a whitelist). -
Every item carries
official_url,sourceandattribution(EUR-Lex: Decision 2011/833/EU, CC0 metadata, CC BY 4.0 consolidated texts). Snippets ≤ 300 characters, plain text. -
Raw HTML is never stored or rendered:
htmltext.html_to_textfirst; the consoleesc()s it. -
REST and MCP share
services/legal.py; don't add logic to either edge. -
MCP auth is a bearer app token only (no cookie — the endpoint must not be a cross-site target) and goes through
moderation.assert_may_use, like every REST route. -
OCR engines are optional. Nothing Paddle/Tesseract in
requirements.txt(deploy_check fails); never Surya, MinerU, marker, PyMuPDF (the license gate denies them by name). Works with OCR off. -
Tests never call a real source —
tests/fakes.py(httpx MockTransport) only.scripts/live_check.pyis the manual live probe (REST's code path, a hard request budget). -
Test with AND without local infrastructure.
tests/infra.pynames the box's states as profiles (bareLIVE only ·fresh·index_only·index_graph·full·graph_partial·vectors_partial·rebuild_pending·upstream_down·upstream_timeout·graph_no_aliases·aliases_partial;aliases= the 0010 table's state), built from the search fixture and the fakes; a test takes theinfrafixture (narrow with@pytest.mark.infra(...),--infra=,INSIDER_INFRA).tests/test_infra_matrix.pyis the invariants suite (shape, the named code first,rank_priorhonesty, vectors only when complete,index_*notices exactly when a local source cannot serve, nothing built/downloaded/loaded in a request, CELEX opens, charset, memory). Every new feature that depends on local infrastructure is tested inbareandfull(CI'sinfra-matrixjob), plus the degraded profile of its component when there is one — and a new component gets its states added toProfileand the invariant it promises added to the matrix. -
Title search is inflection-aware (
integrations/plstem.py, in-house, permissive): ELI gets the light stem of the longest word and the titles are filtered client-side (SearchPage.next_offsetcounts ELI's rows); CELLAR gets prefix matches only for stems of 5+ characters (shorter ones as spelled-out case forms), drops the commonest legal words, and runs the text match first in a sub-select capped atFTS_CANDIDATES— a short prefix on a frequent stem timed CELLAR out. Don't send the query verbatim again — that is the "ochrona danych osobowych finds nothing" bug. -
The index stores Python stems, so
plstem.VERSIONguards it. Bump it with ANY change tostem()'s output: an index records the version it was built with, one from another version is notready()(search goes live),update()refuses to mix stems, andindexing.ensure_index(every scheduler tick) rebuilds it from Postgres, with no download. The masculine-personal plural alternations (sygnaliści/sygnalista, studenci, autorzy, prawnicy, biolodzy, sędzia/sędziów) are deliberately narrow —tests/test_plstem.pypins the look-alikes that must not merge (części, granicy, młodzy, narzędzi, lekarzy, żołnierzy). -
Language analysis goes through the analyzer registry (
integrations/analysis.py):words()is the ONE tokeniser; each language'sAnalyzer= a dictionaryLemmatizer(todaylexicon.Lexiconover sjp.pl's inflection list, CC BY 4.0 — never GPL/LGPL/MPL data) with the rule-based stemmer as the fallback (plstem forpl), chosen per document (row["lang"],TextIndex(langs=…)). Adding a language = aDataPackageinanalysis.PACKAGES+ aregister()call (+ optionallythesaurus/<lang>.tsv) — never a change totextindexor the importers. The lexicon is BUILT byscripts/build_lexicon.pyin the Dockerfile (best effort; never committed —backend/lexicon/is ignored); tests buildtests/fixtures/odm_fixture.txtin conftest, offline. An ambiguous form is ONE token (mama|miec,lexicon.SEP), so the text fields use tantivy'swhitespacetokenizer. The thesaurus is query-side, hand-reviewed, lemmatised by the same analyzer; a variant weighsEXPANSION_BOOST. Partial matches (PARTIAL_SHAREof the words) answer only when no part holds every word, flaggedpartial+ thepartial_matchesnotice.analysis.ident()(stemmer version + lexicon build) is recorded inindex.json. -
The previous index serves until its rebuild is swapped in.
ready()= can answer (a format inREADABLE, today'splstem.VERSION);current()= built exactly as today's code builds it;rebuild_pending()= ready and not current. The rebuild goes into<name>.newand is renamed in, while searches read the old index with the schema and analysis of its own format (format 2 = plstem only). Between the two renames_live()serves<name>.old; a worker whose directory vanished under a search reopens and asks again. Importers write only into acurrent()index (update()refuses to mix analyses). Keep a format inREADABLEuntil no box can still hold it. -
textindex.FORMATguards what a document holds the wayplstem.VERSIONguards the stems: bump it with any change to the fields or their analysis (an index of another format is notcurrent(), andensure_indexrebuilds it from Postgres while the old one still answers if its format is inREADABLE). Format 3 (2026-10-21): analysis terms (lemmas,a|bambiguity tokens), thewhitespacetokenizer, each row in its own language. Format 2 (2026-10-21): the title is the act's NAME (dzu_md.search_title, no notice boilerplate), plushead(a carried chapter heading) andlead(the first sentence) fields, the body keeps function words (positions for the exact phrase; a query never MATCHES on them), and a storedprior(dzu_md.act_prior: codes up; amending acts, notices and acts no longer in force down). Ranking = BM25 title > head > lead > body, + phrase/pair proximity (slop 2) + the exact phrase as typed, × prior × breadth; on a subject query (one that names no act) × what the act IS by its name (rank.RankPrior.group_prior: up toINSIDER_RANK_TITLE_MATCHfor the query's words in the act's name, rarer words weighing more;INSIDER_RANK_SPECIAL_ACTfor an act "o szczególnych rozwiązaniach …"), and an act's shown articles put the one opening a unit HEADED by the query's words first (INSIDER_RANK_HEAD_FIRST: k.c. art. 415 for "odpowiedzialność za szkodę" via the thesaurus' "czyn niedozwolony") — never its rank. Thesaurus variants reach a format-2 index too, through its own (plstem) analysis. The regression set and the offline evaluation aretests/search_eval.py+tests/test_search_quality.pyovertests/fixtures/search_eval.json.gz(a slice of real acts;scripts/build_search_fixture.pyrebuilds it from hand-downloaded files) — runpython tests/search_eval.pyfor the top-3 table after any ranking change.plstem.STOPWORDSare true function words only;eurlex.FTS_COMMON("umowa", "prawo"…) is CELLAR SPARQL's list and never the local index's. -
Every dataset has its OWN cron variable; there is no interval and no shared default (
services/schedule.py, croniter MIT + tzdata Apache-2.0):INSIDER_DZU_MD_SCHEDULE,_ELI_INFORCE_,_CELLAR_,_CELLAR_FULL_,_CELLAR_CASELAW_,_SAOS_DUMP_,_INDEX_REBUILD_SCHEDULE, plusINSIDER_SAOS_DUMP_FIRST_WINDOW, all read inINSIDER_SCHEDULE_TZ(Europe/Warsaw).config.pyvalidates every one at startup and names the variable. Due = the last fire time is after the last start (attempted_at), so a missed run happens ONCE. Croniter steps through naive wall time and only then is a fire placed in the zone (its own tz arithmetic slipped an hour across DST —tests/test_schedule.pypins both changes). dzu_md runs at 07:15, not 05:00: its upstream bot commits ~05:00 UTC. A delta onlyupdate()s the changed groups; a rebuild for another format / analysis waits forINSIDER_INDEX_REBUILD_SCHEDULE(the old index answers; imports write Postgres only meanwhile,index_writable()), a missing index builds at once. Outage notices (legal.outage_notices) only when a local source truly cannot serve. -
An interrupted import resumes in minutes, not an interval later (
indexing.unfinished,RESUME_AFTER): the box's firsteli_inforcepass stopped at 57 of 2 411 acts on a deploy anddue()waited 24 h.eli_inforcealso waits fordzu_md's FIRST full pass (after=) and is due the tick it ends — a text the mirror holds is never fetched from ELI. -
Filters are scoped by kind (
base.JUDGMENT_FILTERS/ACT_FILTERS): a court never drops acts, a publisher / in-force never drops judgments;filter_scopereports where each applied, and a filter outside a source's kind is not "unsupported" there. -
PDF-only acts (every Dz.U. act since 2025) get the PDF text layer inline; only a scan is queued for OCR. SAOS gets one request per question (
client_options: 35 s read, no retry) and is aslowsource: aprogressivesearch defers it (pending[]+ a signed, user-bound ticket forGET /search/pending), otherwise it is waited for underINSIDER_SLOW_SOURCE_BUDGET_SECONDS. -
SAOS has no Supreme Court rulings after 2016:
legal.SN_NOTICEgoes intonotices[]for judgment searches, court=SN and SN case numbers (citations.is_supreme_court_case), and replaces an emptyresolve. Never drop it to make an answer look complete. -
EUR-Lex asks acts and judgments separately (one SPARQL query per sector, no retry), so an all-kinds search always shows EU acts; act details (validity, consolidated version) are a separate, best-effort, cached call — never part of
fetch. -
The User-Agent never carries an IP-style host (
http.contact_is_safe): ELI's firewall 403s it. -
Every EU text carries "© European Union, https://eur-lex.europa.eu" and the conversion note.
-
The reference graph (
services/legalref.py+legalref.lark,services/legalgraph.py,indexing.GraphJob; ideas from tobayah/legal-memory, Apache-2.0, CREDITS.md). Citations are parsed by the lark grammar — a regex only finds where "art." starts; don't grow regexes back into the parser. Precision over recall: a citation of the act itself whose article is not there makes no edge. Storage is Postgres only (legal_ref,legal_ref_count,dzu_article.path) — no graph DB, no in-memory graph in production:trace_pathis the store's recursive CTE (depth- and row-capped);MemoryIndexStore.shortest_pathis only its DB-free twin. The job reads ONE act at a time (the 3 GB cap;test_the_job_holds_one_act_at_a_time) and its cursor keeps a fingerprint per act; bumplegalgraph.VERSIONwith any change to whatbuild_actwrites. Amending acts, superseded t.j. and notices are never sources. Counts are rebuilt by one GROUP BY after each build (recount) and read by primary key (the hit counts, the in-degree prior). -
The alias table (
services/aliases.py,article_alias, alembic 0010,indexing.AliasJob) is an ACCELERATOR, never the only path:resolveasks it first (locate: "alias") and falls back to the act's text (locate: "outline") or the SAOS/CELLAR search (locate: "search") when the table is missing, empty, partial or lacks the key — and LIVE mode never touches it. The response keys are identical either way (legal.ARTICLE_FIELDS); keep them so. One act group is swapped in ONEreplace_aliasestransaction (a new t.j. re-points every key at once); the job reads one act at a time and SAOS in keyset pages (test_the_build_holds_one_act_and_one_page_at_ a_time); bumpaliases.VERSIONwith any change to what a row holds. EU common names live inintegrations/eu_acts.py(reviewed data, likecodes.py).tests/test_aliases.pyruns every resolve behaviour in each infrastructure state (bare…full) — add new ones there. -
/graph/*is server-rendered and runs under the console's CSP, UNCHANGED (the owner rejected NiceGUI over'unsafe-eval'; never relax the policy for these pages). Jinja2 autoescapes everything; graph data reaches the browser only as{{ graph|tojson }}in a<script type="application/json">island;frontend/graph.jsdraws it and asks htmx for the panel. htmx is configured in a meta tag (allowEval,allowScriptTags,includeIndicatorStylesfalse,selfRequestsOnly) — neverhx-on,js:,hx-varsor an inline handler (tests/test_graph_pages.pygreps the templates). Python decides what is drawn (the 500-node cap, depth, filters). Every route depends onget_current_user, every route is a GET, every URL is relative (panel?…,../vendor/…;/graphredirects to the relativegraph/), so ROOT_PATH needs nothing;/graphis inedge.API_PATHS(never the console's files) and gets the same CSP as the console. -
The act-level views (
/graph/acts+acts/view+acts/panel,/graph/top;legalgraph.acts_view/act_panel/top_articles, the stores'act_links/top_acts/cited_articles) are LIVE GROUP BYs overlegal_ref's two indexes — no aggregate table. Measured on the box (142k edges, 19.6k resolved cross-act): top-200 among 64 ms, a hub's neighbourhood 28 ms at depth 1 and 50 ms at depth 2, an act's most-cited articles 7 ms; a precomputed act-pair table saved ~40 ms on the top-N view only (local, synthetic 142k) — not worth a nightly table that can be stale. Revisit if the cross-act edges grow tenfold. Bounds are Python's (ACT_NODES500,ACT_LINK_ROWS,ACT_FRONTIER, depth ≤ 2,TOP_ARTICLES,TOP_MINI); node size (act PageRank) and edge width (weight) are computed server-side on log scales. Until the graph's first complete build — LIVE mode, a fresh install, missing tables — they answer 200 with "Graf jeszcze się buduje" (legal.GraphBuilding), never a 500. Layout is Cytoscape's built-incose(fcose would bring cose-base + layout-base; not needed at ≤ 500 nodes). Every page under/graph/must stay ONE level deep (../vendor/…in base.html), hence/graph/top, not/graph/act/top.graph.jscarries the pages' EN dictionary andwindow.applyLang(the console's rules: text nodes and title/placeholder/aria-label from the Polish source, never innerHTML).
Invariants — preserve these
-
A cited answer is verified, not trusted (
services/grounding.py, README "Models"). The prompt (rules + a grounded example + a REFUSAL with the right act present) is data inapp/ai/prompts/answer.json— keep the refusal example, it is what stops invented article content.verifydrops every sentence whose art./§/ust., date or act number is not in the passage it CITES, or whose lemmatised words are not supported by it; nothing left = refused. Search the whole context before calling something invented (amending-act titles quote EU acts). The graph only WIDENS the passages (one hop, after retrieval's,RankPrior.activeguard) — never replaces.answer_questionstays optional: the MCP facts tools are the default reader path. -
NEVER add logic to a shim.
models/__init__.py(its core re-exports),services/auth.py,services/authz.py(nodestenancy only — insimpleit is local logic),services/audit.py,db.py,errors.py,security.pyandenums.pyexist so call sites keep their import paths. A shim may only: import fromdredd_core, bind names (authenticate = _service.authenticate), declare app-only constants (theinsider_pat_token prefix), wire this app's settings into a core policy object, and list__all__. Behaviour belongs in core: change dredd-core, tag it, repinrequirements.txt— and only then use it here. A rule written into a shim is a rule the siblings don't get and the next core upgrade silently overwrites. -
Core is configured, not subclassed. App-specific bits stay app-side and are passed in — e.g.
AuthPolicy(session_ttl_hours=..., app_token_prefix=APP_TOKEN_PREFIX)built fromconfig.get_settings(), the session cookie's name (SESSION_COOKIE_NAME), FastAPI exception handlers that render core'sAppErroras Problem Details. The platform shape is configuration too, not a fork:identity_writes_enabled/local_login_enabledon that same policy, andModerationPolicy(module_slug=..., shared_permissions=...)inservices/moderation.py, all derived fromsettings.shares_identity. -
Strict layering. No
select(...)/db.add/db.executein a router. A lonedb.get(Model, id)by primary key is acceptable. Services own every domain rule. -
services/authz.pyis the only access authority. Innodestenancy it re-exportsdredd_core.authz(assert_can_read/assert_role; list screens filter throughreadable_node_ids, not a per-row check). Insimpletenancy it is a local module (can_read/assert_can_read/assert_can_write/assert_moderator, each taking theSessionfirst, because the top of the model is now a tier the database answers rather than a column on the person). Call it before every read and write. No access → 404, never 403 — the existence of a record can itself be privileged. -
Three words for what a person may do, and only these three. ADMINISTRATOR is platform-wide (
app_user.is_admin); MODERATOR administers exactly one module; USER may use exactly one module. The last two are onemodule_permissionrow the hub writes, and the fourth answer is no row, which is the default for everybody and means no access to this app at all. That last one is the behaviour, not a detail:deps.get_current_usercallsmoderation.assert_may_useright after the token-scope check, so every authenticated route is covered by one call and no new route can forget it. Without it somebody with a platform account reaches every screen here, sees nothing, can write nothing — and has been refused by nothing, which is the absence of an access decision rather than one. Keep that call unconditional: standalone, core answers"user"for everybody and emits no SQL, which is exactly what lets one guard serve both shapes. This app READS those rows and never writes them —permission_writes_enabledstays False, and the enforcement is the missing grant, not the router. Guard every administration route withdeps.require_moderator, never withis_admin: a grep foris_adminunderapp/routers/should come back empty except where a response serialises it for display. Standalone, ADMINISTRATOR and MODERATOR are the same thing, everybody is a USER, andservices/moderation.pyanswers without emitting a single query.MODULE_SLUGis what keys a permission row, and it is not always the same string asinsider: a module slug is a URL path segment, so the hub'smodule_permissiontable holds it to^[a-z0-9][a-z0-9-]{0,39}$— hyphens yes, underscores no — while a schema name is the reverse.config.pyrefuses a slug that table would reject, and it has to, because this app only ever SELECTs by it: an illegal one raises nothing here, it simply makes the query match no row for ever — and no row is no access, so nobody but a platform administrator could open the app. -
A module reads identity; the hub writes it. On a platform this app's runtime role holds a column-restricted
SELECTonapp_user(nopassword_hash),SELECTplus a three-columnUPDATEonsession,SELECTand nothing else onmodule_permission, and noINSERTanywhere — a role that could insert asessionrow could mint a working credential for the administrator, and one that could writemodule_permissioncould admit anyone, promote anyone and promote itself. TheAuthPolicy/ModerationPolicyflags are the sentence at the edge (a clean 409 instead of a Postgres permission error dressed up as a 500); the grant is the enforcement. Never add a write path to accounts, sessions or permissions here, and never "fix" a permission error by widening the grant — the hub already has the route you want. -
Append-only audit. Write through
dredd_core.audit.record. The runtime role holds no UPDATE/DELETE/TRUNCATE onaudit_log(enforced by0002_runtime_grants).migratorowns DDL; the runtime role is DML-only. This is a confidentiality control, not an ops convenience — never grant the runtime role DDL or audit mutation. Evidence tables are named once, inmodels/__init__.py(APPEND_ONLY_TABLES/NO_DELETE_TABLES); a table missing there is fully writable. -
Grants go through
runtime_grants_sqland fail loudly.op.execute(runtime_grants_sql( get_settings().db_app_role, append_only=APPEND_ONLY_TABLES, no_delete=NO_DELETE_TABLES))— never a hand-written GRANT block, never one that skips silently when a role is missing. It refuses to run as a superuser or the platform admin, raises when the role is missing or a grant did not take, and strips the API roles (anon/authenticated/service_role, what a provider's auto-generated table API connects as). Every revision that creates a table ends with that call (GRANT ... ON ALL TABLESonly covers the tables that exist when it runs). -
Role names are configuration, per app. The runtime role is
DB_APP_ROLE(applocally and in CI,insider_appin the shared managed database, next toinsider_migrator) — role names are cluster-wide there, and generic names would let one app undo another's revokes. Nothing else in the app names a role. -
Own schema, never
public, nothing schema-qualified. In the shared databaseinsideris owned by the migrator and first on both roles'search_path(set bypython -m dredd_core.managed provision), soalembic_version, enum types and tables all land there. Don't qualify names in code or migrations;create_all's checkfirst andcreate_enum_typesthen only see this app's schema. -
Never migrate as
postgres(or any superuser / platform admin): objects would be owned by it, and0002refuses. Migrations run as the migrator only; on a managed database the long-running backend gets no migrator credentials (docker-compose.managed-db.ymlblanks them — an in-app restore would be an explicit, documented opt-in; prefer a one-shot container). -
One TLS rule, from core.
config.pyappliesdredd_core.db.require_verified_tlsto both URLs: a database host counts as local when it is"",localhost,127.0.0.1,::1,postgresor listed inDB_LOCAL_HOSTS(comma-separated, optional); every other host must carrysslmode=verify-full(withsslrootcert, or the system trust store) or the app refuses to start. No provider host lists, no other opt-out — don't add one. -
TLS only through
make_engine. Every engine — runtime, Alembic (make_engine(url, poolclass=NullPool)online,strip_tls_params(url)offline), seed and any script — goes throughdredd_core.db.make_engine, nevercreate_engine: pg8000 ignores libpq'ssslmodeand silently falls back to plaintext. One-shot processes useNullPool; the backend's pool comes fromDB_POOL_SIZE/DB_MAX_OVERFLOW(the shared database's connection limit is shared by every app).alembic/env.pynever passes the URL throughconfig.set_main_option(its%-interpolation breaks percent-encoded passwords). -
A pooler's session mode, never its transaction mode. Through a provider's pooler use session mode (port 5432 on the poolers the family knows) or the direct host — never a transaction-mode port (6543 there). Some poolers want the tenant in the user name:
<role>.<tenant>, andDB_APP_ROLEis the part before the dot.deploy_checkfails on 6543, on a non-verify-full URL and on apostgresuser. -
PostgreSQL 16 and 17. The local stack runs 16, managed providers commonly run 17; CI runs the suite on both, and
managed-dbrehearses the shared-database path on 17. -
dredd-core ships models, not migrations. Importing
dredd_coreregisters the identity and org-tree tables on the sharedBase.metadata; this app owns its0001. Because core's enum columns are declared withcreate_type=False, the native types must exist first:create_enum_types(conn)(core's enums plus this app's own, once its models are imported) →Base.metadata.create_all(conn), then0002's grants. Adding a model or an enum needs no change to0001— both are read off the metadata;tests/test_migration_parity.pyguards that the model is imported. A database migrated before the model existed still needs a new revision for it. -
Every revision after
0001must be idempotent (checkfirst=True,IF [NOT] EXISTS, catalog checks):0001builds from the live metadata, so on a fresh database it already has the current shape and a plainop.create_tablethere fails. And never change what0001creates without a follow-up revision for databases migrated before — editing0001alone changes fresh installs and silently leaves every existing database behind. That is exactly how Galena'snode_kind(native enum → text) broke existing databases. A table a later revision creates must also be granted there — end the revision with the sameruntime_grants_sql(...)call as0002(and name the table inAPPEND_ONLY_TABLES/NO_DELETE_TABLESfirst if it is evidence). -
A core upgrade can change the schema. If a repin adds or alters a core table, write a new revision in this repo for it — core tags describe models, they do not migrate your database.
-
Every model must be imported in
models/__init__.pyor it silently never gets a table. -
(
nodestenancy) A leaf node and its domain row are created together, in one transaction, by a domain service — never by the nodes router. A leaf without its row is an orphan the authz resolver can see but nothing can use. -
Sessions are server-side, so logout/deactivate is an instant kill-switch. Deactivating a user must also revoke their sessions. Sessions live in this app's own tables only.
-
Token scope is enforced in
deps.get_current_userand nowhere else. Every authenticated route depends on it, so one check covers all of them and no future route can forget it. -
Cookie-authenticated writes must be same-origin —
deps.refuse_cross_site_write, registered once as an app-wide dependency inmain.py, so login, logout and every future route are covered. SameSite=Lax does not stop a same-site sibling app on another subdomain; the guard checksSec-Fetch-Site, andOriginagainstHostwhere browsers omit the former (plain HTTP, older Safari). Bearer requests andCORS_ALLOW_ORIGINSentries are trusted. Deployed under a path prefix of a shared origin this guard separates the platform from foreign sites only, never one module from another — a page at/siblingis same-origin with this app, so both signals pass. That is what one account wants; don't "restore" a guard that cannot work there. The consequence is that an XSS in any console on that origin can drive every module's API with the user's cookie, which makes "untrusted bytes never execute in-origin" a platform-wide guarantee rather than a local one. And never add an entry toCORS_ALLOW_ORIGINSonce the family shares an origin —deps.pyreturns early for any listed origin, bypassing both signals. -
Settings are a closed, typed set (
services/settings.SPECS). Add a key there with its type and bounds; never reintroduce an endpoint that writes any key it is given. -
Bad input is a 422, never a 500. Type path ids as
uuid.UUIDand vocabularies as their enum in the schema, so FastAPI refuses them before a service builds a query or an enum from raw text.tests/test_integration.pyholds this floor — extend it for the real domain, don't delete it. -
Nonemeans "not supplied", never "blank it" in a partial update. Keep an explicit list of clearable fields if a user must be able to empty something. -
Errors are RFC 9457 Problem Details; raise
dredd_core.errorstypes from services, render them in one handler. Stack traces hidden whenAPP_ENV=production. -
Console security:
esc()every dynamic value; bearer token in memory only, cookie session primary; nothing loads from a CDN (the CSP has no third-party origins); external links open withrel=noopener. -
Brand = Open Color
teal#099268, confined to identity — the app mark, icon tiles, the avatar, the focus ring. Buttons, nav and toolbar glyphs stay monochrome; brand everything and nothing stands out. Semantic ok/warn/err is a separate axis. -
Core stays permissive. Apache-2.0; CI denies GPL/AGPL/SSPL. Copyleft or heavyweight components are optional sidecars, never core.
-
No build step for the console.
Gotchas
- Installing needs credentials.
dredd-corelives in a private repo;pip install -r requirements.txtfails with an authentication error unless git can reach it (CI uses theDREDD_CORE_TOKENsecret; locally, your own GitHub credentials). - Tenancy
simple: importingdredd_coreregistersnode,permission_grantandfavoriteregardless, so a flat single-tenant app still creates those three tables. They stay empty and unused — that is expected, not a bug. Don't try to suppress them. - Some poolers want
<role>.<tenant>logins, and some providers ban the client IP for a while after a few wrong passwords in a row — nothing retries a failed migration on purpose. Percent-encode passwords in URLs. The managed-database runbook isdb/managed/README.md. - On Windows, write
.envwithout a BOM (PowerShell'sOut-File -Encoding utf8adds one, and pydantic-settings folds it into the first key name) — use[System.IO.File]::WriteAllText(...). - Syntax-check the console after editing it:
node --check frontend/app.js. A duplicateconstinside one function silently stops the whole file parsing, so every function defined after it disappears — and the symptom is a screen that renders nothing, with no console error. - Never transition
visibilityover a duration or with a delay; the off-canvas drawer gets stuck when frames are throttled.transformtransitions;visibilityflips instantly. - Name model modules so they cannot shadow a stdlib module (
timelog.py, nottime.py).
Status
Domain built (2026-10-20) on dredd-core v0.15.0: ELI + SAOS + EUR-Lex adapters, federated search,
citations, cache, OCR tiers/queue, REST, MCP at /mcp, the ui/v1 console. The scaffold's example
entity is gone (0005 drops record where an old database has it). Standalone the backend is
published on 8101 (family scheme: Galena 8021, Sygna 8041, Compass 8061, Counsel 8081, Insider
8101; on the platform the modules publish nothing).
INDEXED mode (Phase 2, 2026-10-21, branch indeks): dziennik-ustaw-md + ELI in-force gap-filler +
SAOS dump into tantivy, off by default (INSIDER_INDEX_ENABLED). CELLAR importer (branch
cellar-import, 2026-10-21): EU acts in force + optional CJEU case law, replacing the EUR-Lex dump
seam.