Files
adminandClaude Opus 5.5 4c6e77017e Ground cited answers: few-shot refusal, a verifier, graph expansion, an eval
Brings in tobayah/legal-memory's RAG findings (Apache-2.0, CREDITS.md):
- the answer prompt is data (app/ai/prompts/answer.json, PL + EN) with two
  worked examples, the second a REFUSAL although the right act is present;
- services/grounding.verify drops every sentence that cites nothing, a
  passage out of range, an art./section/ust. number, date or act number its
  CITED passage does not hold (invented vs miscited after searching the whole
  context), or whose lemmatised words its passage does not support; nothing
  left = refused; a `verification` block goes to REST and MCP;
- retrieval adds up to INSIDER_ANSWER_GRAPH_EXPAND articles one hop away in
  legal_ref, only while RankPrior.active() (the rank_prior guard);
- tests/answer_eval.py: a misbehaving fake generator per failure mode, plus
  real questions for --live runs; infra-matrix test in bare and full.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 00:40:41 +02:00

338 lines
22 KiB
Bash
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ─────────────────────────────────────────────────────────────────────────────
# Insider — copy to .env and edit. On Windows write it WITHOUT a BOM:
# [System.IO.File]::WriteAllText("$PWD\.env", (Get-Content .env.example -Raw))
# (PowerShell's Out-File -Encoding utf8 adds a BOM, which pydantic-settings then
# folds into the first key name and you get a baffling "field required" error.)
# ─────────────────────────────────────────────────────────────────────────────
# Core. Defaults fail closed: production hides error detail. The session cookie's
# Secure flag is auto-detected from the request scheme (see SESSION_COOKIE_SECURE).
APP_ENV=production
# The standalone stack publishes the backend on 8101 (the family's port scheme: Galena 8021,
# Sygna 8041, Compass 8061, Counsel 8081, Insider 8101). On the platform the modules publish nothing.
APP_BASE_URL=http://localhost:8101
# Path prefix this deployment is mounted under. Empty = served at the origin root (this stack).
# ROOT_PATH=/insider runs it as a module of a platform (one origin, one module per path). It is
# HALF of one decision: the front door must STRIP the prefix (Atrium forwards `/insider/*` without it) and
# this backend re-adds it via uvicorn --root-path. Set only one of the two and you get a doubled
# prefix (404s everywhere) or server-generated URLs that escape it. The console needs nothing — it
# derives its API base from the document.
ROOT_PATH=
# ── Database ─────────────────────────────────────────────────────────────────
# Runtime uses the least-privilege `app` role; Alembic uses `migrator`.
POSTGRES_DB=insider
POSTGRES_PASSWORD=change_me_super
DB_APP_PASSWORD=change_me_app
DB_MIGRATOR_PASSWORD=change_me_migrator
DATABASE_URL=postgresql+pg8000://app:change_me_app@postgres:5432/insider
MIGRATION_DATABASE_URL=postgresql+pg8000://migrator:change_me_migrator@postgres:5432/insider
# The runtime role's name (the user in DATABASE_URL); the runtime-grants migration grants to it.
DB_APP_ROLE=app
# The backend's connection pool: at most DB_POOL_SIZE + DB_MAX_OVERFLOW connections.
DB_POOL_SIZE=5
DB_MAX_OVERFLOW=10
# TLS rule: a database host that is not local ("", localhost, 127.0.0.1, ::1 or `postgres`) must say
# sslmode=verify-full in its URL, or the backend, migrate and the seed refuse to start. A private
# database on a trusted network that truly needs no TLS is listed here instead (comma-separated).
# No other opt-out.
DB_LOCAL_HOSTS=
# ── Managed PostgreSQL (the family's shared database; replaces the local postgres) ──
# Runbook: db/managed/README.md. Every app of the family shares ONE managed database; Insider
# lives in schema insider, as roles insider_migrator and insider_app. Provision it
# once, then replace the Database settings above with these, delete the POSTGRES_PASSWORD and
# DB_*_PASSWORD lines (unused there), and start with BOTH compose files:
# docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
# - Host and port: from the provider's connection details. Through a pooler use its SESSION mode
# (transaction mode breaks prepared statements; on the poolers the family knows that is port 5432,
# never 6543), or the direct connection.
# - User: <role>, or <role>.<tenant> where the pooler wants the tenant in the user name. Never the
# platform admin (postgres).
# - TLS: sslmode=verify-full against the provider's root CA (downloaded from its dashboard), which the
# override mounts at /run/certs/db-ca.crt from MANAGED_DB_CA_FILE; leave sslrootcert out to verify
# against the system trust store instead. sslmode=prefer/allow/disable are refused, and so is a
# URL to any host that is not local without sslmode=verify-full (DB_LOCAL_HOSTS above).
# - Passwords: percent-encode every character outside A-Z a-z 0-9 - . _ ~ (e.g. @ -> %40, % -> %25).
# - DB_APP_ROLE: the role in DATABASE_URL without any .<tenant> suffix (migrate refuses otherwise).
# - Pool: count DB_POOL_SIZE + DB_MAX_OVERFLOW + 1 (a seed or check beside the backend) per app, and
# keep the total over every app in the database at or below 80% of its connection limit (the
# provider's own services use the rest): 72 of 90, 48 of 60. Five apps at the defaults take
# 5 x (15 + 1) = 80, which does NOT fit a 90-connection limit: set DB_POOL_SIZE=4 and
# DB_MAX_OVERFLOW=8 in EVERY app (5 x 13 = 65), or size the instance for more. For a 60-connection
# limit set DB_POOL_SIZE=3 and DB_MAX_OVERFLOW=2 in EVERY app (5 x 6 = 30). Through a pooler in
# session mode, its own pool size must be at least DB_POOL_SIZE + DB_MAX_OVERFLOW + 1.
# DB_POOL_SIZE >= 1 and DB_MAX_OVERFLOW >= 0 (0 / -1 would mean no limit, so they are refused).
# MANAGED_DB_CA_FILE=./certs/db-ca.crt
# DATABASE_URL=postgresql+pg8000://insider_app.<tenant>:<app-password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
# MIGRATION_DATABASE_URL=postgresql+pg8000://insider_migrator.<tenant>:<migrator-password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
# DB_APP_ROLE=insider_app
# DB_POOL_SIZE=4
# DB_MAX_OVERFLOW=8
# ── The legal sources (LIVE / federated mode) ────────────────────────────────
# The hosts are fixed in code (api.sejm.gov.pl, www.saos.org.pl, publications.europa.eu); these only
# switch a source on/off and set how politely it is asked. Shown in the User-Agent as
# `Insider/<version> (+INSIDER_CONTACT)` — an e-mail or URL the sources' operators can reach you at.
# SET ON THE PLATFORM: an empty value works but logs a warning at every start-up (the sources then
# see an anonymous client). Never an address with an IP in it (an sslip.io/nip.io host): the Sejm
# ELI API's firewall answers 403 to every request whose User-Agent carries one (seen 2026-10-20).
INSIDER_CONTACT=
INSIDER_SOURCE_ELI=true
# SAOS: its robots.txt disallows /api/. Insider uses it ONLY for user-initiated live queries — one at a
# time, slowly, no crawling, dumps, prefetch or warm-up. Set false to switch it off entirely.
INSIDER_SOURCE_SAOS=true
# EUR-Lex/CELLAR (public SPARQL + content negotiation; no registration). Reuse: Decision 2011/833/EU.
INSIDER_SOURCE_EURLEX=true
# Requests per second and concurrent requests, per source (SAOS is held to ≤ 2 / ≤ 2).
INSIDER_RATE_ELI=2
INSIDER_CONCURRENCY_ELI=4
INSIDER_RATE_SAOS=1
INSIDER_CONCURRENCY_SAOS=1
INSIDER_RATE_EURLEX=1
INSIDER_CONCURRENCY_EURLEX=2
# The overall time budget of one federated search; slower sources answer `timeout`.
INSIDER_SEARCH_BUDGET_SECONDS=10
# A slow source (SAOS answers in 22–30 s) is delivered after the fast ones (GET /search/pending) or
# waited for (MCP wait_for_slow), within this budget. Its own request still times out at 35 s.
INSIDER_SLOW_SOURCE_BUDGET_SECONDS=40
# The administrator's AI switches and each person's moderator answer are kept this many seconds
# per worker instead of being read on every search (0 = every time). A settings save is visible at
# once in the worker that took it, everywhere else within this TTL.
INSIDER_AI_SWITCH_CACHE_SECONDS=30
# HMAC key for pagination cursors (e.g. `openssl rand -hex 32`). Empty = random per process.
# SET ON THE PLATFORM (a secret — never commit it): with an empty value every worker and every
# restart has its own key, so a cursor from one is refused by the next; a warning says so at start-up
# (naming the setting, never a value).
INSIDER_CURSOR_SECRET=
# How often expired source_cache rows are deleted, in seconds; 0 = never. Safe with several workers
# (a Postgres advisory lock lets one purge at a time).
INSIDER_CACHE_PURGE_SECONDS=3600
# ── INDEXED mode (local datasets + a tantivy full-text index) ──────────────────
# Master switch. false (default) = LIVE only, exactly as before: nothing is downloaded, no index is
# opened. true = the dataset importers below run on their schedules (each has its own off switch),
# and search uses the local index once it is built and fresh, falling back to the live sources.
# Disk (estimates): acts ~0.5–1 GB in Postgres + ~0.3–0.6 GB index; the full SAOS dump ~10–14 GB
# in Postgres + ~4–6 GB index. README "INDEXED mode".
INSIDER_INDEX_ENABLED=false
# Where the indexes live; empty = <DATA_DIR>/index. Disposable: rebuilt from Postgres when missing.
INSIDER_INDEX_DIR=
# ── When each dataset updates: cron (min hour day month weekday), several joined by ";", read in
# INSIDER_SCHEDULE_TZ. Every one is validated at startup — an invalid one refuses to start, naming
# its variable. A run missed while the box was down happens once at the next tick.
# The zone every schedule (and the SAOS first-import window) is read in; DST-aware.
INSIDER_SCHEDULE_TZ=Europe/Warsaw
# dziennik-ustaw-md: its bot commits ~05:00 UTC (07:00 Warsaw in summer) — 05:00 would be a day behind.
INSIDER_DZU_MD_SCHEDULE="15 7 * * *"
# ELI in-force acts: daily (one listing; only acts whose changeDate moved are fetched).
INSIDER_ELI_INFORCE_SCHEDULE="0 5 * * *"
# CELLAR acts: the daily delta (works CELLAR modified since the last pass).
INSIDER_CELLAR_SCHEDULE="0 5 * * *"
# CELLAR: the full listing pass (finds acts that left force) — Sundays.
INSIDER_CELLAR_FULL_SCHEDULE="0 5 * * 0"
# CELLAR CJEU case law (when INSIDER_CELLAR_CASELAW is on): the daily delta.
INSIDER_CELLAR_CASELAW_SCHEDULE="0 5 * * *"
# SAOS dump: the daily delta, once the first full import is done.
INSIDER_SAOS_DUMP_SCHEDULE="0 5 * * *"
# SAOS dump: the FIRST full import (several nights) runs only inside this window.
INSIDER_SAOS_DUMP_FIRST_WINDOW=23:00-05:00
# An index built another way (a deploy changed its format/analysis) is rebuilt then; the old one answers meanwhile. A missing one builds at once.
INSIDER_INDEX_REBUILD_SCHEDULE="0 5 * * *"
# The reference graph (article→article, parsed from the indexed acts — no request to anyone): it also
# runs after every dziennik-ustaw-md / ELI in-force sync, and never before dziennik-ustaw-md's first pass.
INSIDER_LEGAL_GRAPH_SCHEDULE="0 5 * * *"
# The reference graph itself (README "Reference graph"): `legal_ref` rows, about one per article.
INSIDER_LEGAL_GRAPH=true
# The alias table (README "Article aliases": kc:483, rodo:6, sig:III CZP 12/20 -> one lookup per
# resolve): after every dataset / graph sync, and on this schedule.
INSIDER_ARTICLE_ALIASES_SCHEDULE="30 5 * * *"
INSIDER_ARTICLE_ALIASES=true
# "Cited in case law" (README "Cited in case law"): judgments citing articles, parsed from the SAOS
# sections with the graph's grammar, after saos_dump and the graph, and on this schedule. Needs
# INSIDER_LEGAL_GRAPH. The job reads INSIDER_CASE_REFS_PAGE judgments (with their texts) at a time.
INSIDER_CASE_REFS=true
INSIDER_CASE_REFS_SCHEDULE="45 5 * * *"
INSIDER_CASE_REFS_PAGE=100
# A search prior for articles often cited in case law: x (1 + this x ln(1 + judgments)), only once
# the case-law pass is complete. 0 = off (search_eval showed no gain).
INSIDER_CASE_LAW_PRIOR=0
# Ranking (README "Ranking"): once the graph's PageRank pass is complete, an article's score
# x (1 + this x ln(1 + its PageRank, 1.0 = average)); until then the naive prior alone. 0 = off.
INSIDER_LEGAL_GRAPH_PRIOR=0.05
# The same for an act's PageRank, on the live (ELI) results, which are acts.
INSIDER_LEGAL_RANK_ACT_PRIOR=0.1
# PageRank is used only when its pass is on the graph's last finished build and the graph's parsed
# acts cover this share of its sources.
INSIDER_LEGAL_RANK_MIN_COVERAGE=0.95
INSIDER_LEGAL_RANK_DAMPING=0.85
# What an act IS, on a subject query (graph or no graph): an act whose name holds the query's words
# x up to this (rarer words weigh more), an act "o szczególnych rozwiązaniach ..." x the second;
# 1.0 = off. And the articles shown for an act: those opening a chapter whose heading holds the
# query's words first (the general rule before the special ones).
INSIDER_RANK_TITLE_MATCH=1.5
INSIDER_RANK_SPECIAL_ACT=0.5
INSIDER_RANK_HEAD_FIRST=true
# dziennik-ustaw-md (CC0): Dz.U. 2025+ and older PDF-only acts as Markdown. One ~1 KB request per
# check; a new commit fetches index.csv + the changed files (first sync ~7.2k files, ~30 min).
INSIDER_DZU_MD_SYNC=true
INSIDER_DZU_MD_RATE=4
INSIDER_DZU_MD_STALE_HOURS=72
# The acts IN FORCE with their current consolidated text from ELI, where no CC0 mirror has it (the
# codes and the major acts). Base acts of these ELI types; amending acts are skipped.
INSIDER_ELI_INFORCE_SYNC=true
INSIDER_ELI_INFORCE_RATE=2
INSIDER_ELI_INFORCE_TYPES=Ustawa,Konstytucja
# SAOS's DUMP API — only this ingestor uses it, never a search. One request in flight, a pause
# between pages; resumable. The first full import takes days (INSIDER_SAOS_DUMP_FIRST_WINDOW).
INSIDER_SAOS_DUMP_SYNC=true
INSIDER_SAOS_DUMP_PAGE_SIZE=100
INSIDER_SAOS_DUMP_PAUSE_SECONDS=5
INSIDER_SAOS_INDEX_STALE_HOURS=96
# CELLAR (EU law, anonymous — no EU Login account): every regulation, directive and decision IN
# FORCE with the text of its newest consolidated version (Polish, else English), from the
# Publications Office's SPARQL endpoint + the 303 text fetch. A full listing pass and a daily delta
# (CELLAR's modification dates) on the schedules above; one request in flight, every redirect hop counted
# against the rate (≤ 2). First import ~35k acts ≈ 20 h at 1 req/s; ~1 GB Postgres + ~0.3 GB index.
# (Replaces INSIDER_EURLEX_DUMP_SYNC, which is gone; a leftover value is ignored.)
INSIDER_CELLAR_SYNC=true
INSIDER_CELLAR_RATE=1
INSIDER_CELLAR_STALE_HOURS=96
# CJEU judgments (Court of Justice + General Court) from this date on — off by default
# (~25k judgments with a Polish version since 2000: roughly another day of importing).
INSIDER_CELLAR_CASELAW=false
INSIDER_CELLAR_CASELAW_FROM=2000-01-01
# ── Models (README "Models") ─────────────────────────────────────────────────
# Hybrid (BM25 + embeddings) search and reranking, ON with the index. Local CPU models (ONNX), downloaded
# once by the background embedding job into INSIDER_MODEL_CACHE_DIR (default DATA_DIR/models); until
# then — or without them — search is BM25 alone. `none` switches a role off.
INSIDER_SEMANTIC=true
INSIDER_EMBEDDER=local:intfloat/multilingual-e5-small
# off by default (~25 s/query on CPU, README "Models"); with a GPU or a smaller cross-encoder:
# INSIDER_RERANKER=local:onnx-community/bge-reranker-v2-m3-ONNX@onnx/model_quantized.onnx
INSIDER_RERANKER=none
INSIDER_RERANK_TOP=20
INSIDER_RRF_K=60
INSIDER_VECTOR_WEIGHT=1.0
INSIDER_SEMANTIC_DATASETS=dzu_md,cellar
# when the embedding job looks for new/changed parts: cron, in INSIDER_SCHEDULE_TZ, ";" for several
INSIDER_EMBED_SCHEDULE="0 5 * * *"
INSIDER_EMBED_BATCH=32
INSIDER_EMBED_PAUSE_SECONDS=0.2
INSIDER_MODEL_THREADS=2
INSIDER_MODEL_CACHE_DIR=
INSIDER_MODEL_OFFLINE=false
# Query rewriting + cited answers: which model (none by default). Whether they run, and whether a
# question may leave this machine, are switches in Administracja → Modele.
# anthropic:claude-sonnet-5-5 · ollama:SpeakLeash/bielik-11b-v2.3-instruct:Q4_K_M
# openai-compat:https://api.mistral.ai/v1#mistral-small-latest · provider:<name in the hub>[#model]
INSIDER_GENERATOR=none
INSIDER_GENERATOR_API_KEY=
INSIDER_ANTHROPIC_API_KEY=
INSIDER_OLLAMA_URL=http://localhost:11434/v1
# the platform's provider-key secret (the hub's MODEL_PROVIDER_SECRET), for provider:…
MODEL_PROVIDER_SECRET=
# Cited answers are verified sentence by sentence (README "Models"): the share of a sentence's
# lemmatised words its cited passage must hold (0 = no lexical check), and how many articles one
# hop away in the reference graph join the passages (only while the graph is complete; 0 = never).
INSIDER_ANSWER_MIN_SUPPORT=0.35
INSIDER_ANSWER_GRAPH_EXPAND=4
# ── OCR (acts published only as PDF) ────────────────────────────────────────
# auto | paddle_vl | paddle | tesseract | off. The core image has the PDF text layer only; the
# engines come with the `ocr` compose profile (Dockerfile.ocr). Missing engines are skipped.
OCR_ENGINE=auto
# Per-page escalation threshold: a page below it goes to the next engine.
OCR_MIN_CONFIDENCE=0.80
# inprocess (the backend runs the queue worker) | external (the `ocr` profile's ocr-worker does —
# set this when you start that profile) | off.
OCR_WORKER=inprocess
# ── Storage ──────────────────────────────────────────────────────────────────
DATA_DIR=/data
# ── One platform, one account ────────────────────────────────────────────────
# The shared identity schema. Empty — this stack — is STANDALONE: Insider owns its own
# accounts, has its own sign-in screen and its own Users administration, and the three settings
# below do nothing. That is a supported deployment for ever, not a stage to grow out of.
#
# Set IDENTITY_SCHEMA=dredd and this app becomes a MODULE of the platform: `app_user`,
# `session` and `module_permission` live in a neutral schema the hub owns and this app READS. A
# person then has ONE account for everything, signs in once at the hub, and the cookie they got
# there is the cookie this app accepts — one origin, one cookie, nothing to hand over. This app's
# sign-in form disappears (there is no password here), account creation and password changes answer
# 409 pointing at the hub, and app tokens stay listable and revocable but are minted there.
#
# It also starts REFUSING people, which standalone it never does. `module_permission` holds one row
# per person per module, and no row is no access: somebody with a platform account who has not been
# admitted to this one is turned away at the door rather than shown an empty screen. Admitting them,
# and making somebody a moderator of this app, happens in the hub — this app holds SELECT on that
# table and nothing else.
#
# Switching it on is NOT just this line. In order: the platform admin re-renders
# db/managed/provision.sql with --identity-schema / --identity-owner and runs it (the schema, USAGE
# and a search_path of `insider, dredd, extensions` — none of which a migrator may
# do); the hub's own migration creates the tables and grants this app's two roles their tier; then
# `alembic upgrade head` here runs 0003, which merges this schema's accounts into the shared ones by
# e-mail address. Read backend/alembic/versions/0003_shared_identity.py before running it on
# anything you care about — it drops this app's local identity tables, and every session and app
# token with them. db/managed/README.md has the whole sequence.
IDENTITY_SCHEMA=
# This app's slug on the platform — the module a permission row admits somebody to. Only meaningful
# with IDENTITY_SCHEMA set, and it must match the slug the hub uses for this app, or nobody's row
# resolves and nobody but a platform administrator can open it. Note it is NOT always the same
# string as the Postgres schema (`insider`): a module slug is a URL path segment, so the hub's
# module_permission table allows hyphens and refuses underscores, while a schema name is the other
# way round. The scaffolder derived this one from that one; change both or neither.
MODULE_SLUG=insider
# Where people sign in when accounts are shared: the hub's address as a browser sees it, e.g.
# /atrium/. Empty is allowed — the console then says accounts live elsewhere without offering a
# link that goes nowhere.
IDENTITY_HUB_URL=
# The session cookie's name. One account means one cookie: at a cutover every app in the family is
# set to dredd_session. The old name is still read for a while, so renaming it does not sign
# everybody out the moment the container restarts.
SESSION_COOKIE_NAME=insider_session
# ── Auth / sessions ──────────────────────────────────────────────────────────
SESSION_TTL_HOURS=12
LOGIN_MAX_ATTEMPTS=5
LOGIN_LOCKOUT_MINUTES=15
# Empty = auto-detect from the request scheme (Secure over HTTPS only). Never key
# this off APP_ENV — a Secure cookie over plain HTTP is dropped and login "doesn't stick".
SESSION_COOKIE_SECURE=
# CORS — empty by default (same-origin design). Comma-separated origins for a
# separately-served console in dev.
CORS_ALLOW_ORIGINS=
# Who may frame Insider: 'none' (default; X-Frame-Options DENY) or 'self' (SAMEORIGIN, what the
# platform's kit sets). Anything else refuses start-up.
FRAME_ANCESTORS='none'
# ── Bootstrap admin (seed) ───────────────────────────────────────────────────
BOOTSTRAP_ADMIN_EMAIL=admin@example.com
BOOTSTRAP_ADMIN_PASSWORD=admin12345
# ── App tokens ───────────────────────────────────────────────────────────────
# Named, revocable credentials for desktop/CLI clients, so they never store a password.
# The window is an IDLE timeout: every use slides it forward, so a token in regular use keeps
# working while one that is exfiltrated and parked expires on its own.
APP_TOKENS_ENABLED=true
APP_TOKEN_IDLE_DAYS=30
APP_TOKEN_MAX_IDLE_DAYS=365
APP_TOKEN_RENEW_AFTER_HOURS=12
# ── The edge ─────────────────────────────────────────────────────────────────
# No reverse proxy: the backend is published on :8101 (plain HTTP) and is its own edge (app/edge.py).
# uvicorn trusts X-Forwarded-For only from these addresses (default 127.0.0.1). On the platform, the
# front door's address; never `*`.
FORWARDED_ALLOW_IPS=127.0.0.1
# ── OpenTelemetry (opt-in) ───────────────────────────────────────────────────
OTEL_ENABLED=false
OTEL_SERVICE_NAME=insider-backend
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317