The family numbers its ports app / db / static, twenty apart per app (Galena 8012/8014/8021, Sygna 8032/8034/8041, Compass 8052/8054/8061, Counsel 8072/8074/8081), so the stacks run side by side on one machine; :80 collides with a sibling stack on the first `up`. On the platform the modules publish nothing and Atrium's front door alone keeps :80. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
44 KiB
Counsel Scorecard
A self-hosted, single-tenant questionnaire & scoring engine — configurable questions, answer options, weighted questionnaire sets, and append-only responses-with-history — shipped as a complete stack: a FastAPI service on PostgreSQL (full-text search + RBAC + audit), a static admin console (Open Mercato–inspired UI), OpenTelemetry→ClickHouse→HyperDX observability, and CI.
Its reference configuration is Counsel Scorecard — scoring external law firms ("counsel") for an in-house legal department: after a matter closes a reviewer fills in the questionnaire, and each quarterly review cycle rolls those responses into an immutable, explainable composite score per firm, turning relationship-based panel management into a measurable, auditable, defensible process.
License: Apache-2.0 · Status: MVP-0 (qualitative core loop) · ▶ Live demo · 📸 Screenshots
Built from the product/architecture spec in ../Counsel-Scorecard/.
Quick start
cp .env.example .env # then edit every change_me_* value
DREDD_CORE_TOKEN=github_pat_... docker compose up -d --build # postgres → migrate (+ seed) → backend on :8081
The build installs the private dredd-core package, so it needs a GitHub token with read access to it, passed
as a BuildKit build secret: keep it in the shell, never in .env.
Once the backend reports healthy (docker compose ps), open the admin console at
http://localhost:8081/, the API docs at http://localhost:8081/api/v1/docs, and sign in with the
bootstrap admin from your .env. Full walkthrough, observability, and local-dev paths are in
Running it.
Contents
- Live demo
- Screenshots
- Credits & licenses
- Highlights
- Tech stack
- Architecture
- Data model
- Running it
- Configuration
- RBAC
- API reference
- Scoring model
- Local development
- Running as a module of the platform
- Deploying on a managed PostgreSQL
- Tests & CI
- Project layout
- Scope & roadmap
- Security
- License
Live demo
A seeded, backend-free build of the admin console runs in the browser, served by Netlify — no install, no login:
▶ Live demo: https://super-lamington-4749f7.netlify.app/
It's the real frontend/index.html with a lightweight mock API layer injected at build time by scripts/build_demo.py, then built and served automatically by Netlify (see netlify.toml). Try the EN/PL and system / light / dark toggles (top-right) — it follows your OS theme by default.
Highlights
| Requirement | How it's delivered |
|---|---|
| PostgreSQL + Full-Text Search | PostgreSQL 16 with generated tsvector columns + GIN indexes on firm, matter, question, response; pg_trgm trigram fuzzy fallback; one GET /api/v1/search endpoint. |
| Generic questionnaire engine | question → answer_option (possible answers) → questionnaire + questionnaire_question (grouped, weighted set) → response → response_item → response_revision (append-only history). Questions/answers/weights are data, not code. |
| Role controls (RBAC) | Three questions, kept apart. Whether you may OPEN this module at all is a module_permission row naming counsel — no row, no entry — granted in the hub. Whether you ADMINISTER it is that row's role (moderator), or the platform-wide administrator. What you DO here is user_role (legal_ops / matter_owner / viewer) on Counsel's own side table. Server-side sessions give an instant kill-switch. |
| Observability | OpenTelemetry SDK → OTel Collector → ClickHouse → HyperDX unified UI (metrics + logs + traces on one screen). Opt-in. |
| Audit & least-privilege | Append-only audit_log (runtime role has no UPDATE/DELETE); separate migrator (DDL) and app (DML-only) DB roles; Postgres never published to the host. |
| Scoring & fairness | present_i weighted mean with per-evaluation materiality weighting (complexity/value bands); constrained-choice evaluations excluded; firms below min_evaluations stay provisional. |
| Login hardening | Argon2id hashing + app-level lockout after repeated failures. |
| Admin console | Single static HTML/JS file (frontend/index.html, no build step) served same-origin by the backend itself: an Open Mercato–inspired shell — collapsible sidebar nav (responsive off-canvas drawer on mobile), light/dark theme, EN/PL localization (auto-detected), data tables, forms, a command-palette (Ctrl/⌘K) search, and an in-app About page — driving every endpoint. |
| Tested in CI | GitHub Actions runs the suite against a real Postgres (full end-to-end loop) + a pip-licenses gate denying GPL/AGPL/SSPL. |
Tech stack
| Layer | Choice | License |
|---|---|---|
| Language / runtime | Python 3.12 | PSF |
| Web framework | FastAPI | MIT |
| ORM / migrations | SQLAlchemy 2 + Alembic | MIT |
| DB driver | pg8000 (pure-Python) | BSD-3-Clause |
| Database | PostgreSQL 16 | PostgreSQL |
| Search | Postgres FTS (tsvector + GIN + pg_trgm) |
PostgreSQL |
| Passwords | Argon2id (argon2-cffi) |
MIT |
| Instrumentation | OpenTelemetry (OTLP/gRPC) | Apache-2.0 |
| Observability store / UI | ClickHouse + HyperDX | Apache-2.0 / MIT |
| Orchestration | Docker Compose | Apache-2.0 |
Every dependency is permissive (Apache / MIT / BSD / PostgreSQL) — no copyleft at all (not even LGPL), so it clears a corporate legal/IT license scan. The pure-Python pg8000 driver also drops the libpq system dependency.
See CREDITS.md for the full dependency list (what each piece is for) and the design inspirations behind the admin console UI.
Architecture
flowchart TB
user(["Internet / LAN"])
subgraph host["Host — only :8081 is published"]
backend["FastAPI backend<br/>console · API · security headers<br/>routers → services → models (ORM)"]
end
subgraph dnet["Private docker network — expose only, never published"]
pg[("PostgreSQL 16")]
subgraph obs["Observability — opt-in"]
otel["OTel Collector"]
ch[("ClickHouse")]
hyperdx["HyperDX<br/>UI :8080"]
end
end
user -- "HTTP :8081 (TLS: your own terminator)" --> backend
backend --> pg
backend -. "OTLP/gRPC" .-> otel
otel --> ch
ch -. "read by" .-> hyperdx
%% invisible link keeps observability stacked below Postgres (vertical)
pg ~~~ otel
classDef external fill:#eef2ff,stroke:#6366f1,color:#111827;
classDef entry fill:#dbeafe,stroke:#1d4ed8,color:#111827;
classDef svc fill:#dcfce7,stroke:#15803d,color:#111827;
classDef store fill:#fef3c7,stroke:#b45309,color:#111827;
class user external;
class backend entry;
class otel,hyperdx svc;
class pg,ch store;
Strict one-way layering (spec §I.1) — each layer depends only on the one below:
routers/ HTTP, Pydantic validation, auth + RBAC · never touches the DB session
services/ domain logic: scoring, responses, audit · never builds raw SQL
models/ ORM entities, constraints, indexes
Data model
20 tables. The questionnaire engine generalizes the spec's hardcoded criterion/evaluation
tables; the domain tables ground it in the Counsel Scorecard problem.
flowchart TB
subgraph engine["Questionnaire engine — generic"]
question["question"]
answer_option["answer_option"]
questionnaire["questionnaire"]
response["response"]
response_item["response_item"]
response_revision["response_revision<br/>append-only history"]
end
subgraph domain["Domain — Counsel Scorecard"]
firm["firm"]
office["office"]
practice_area["practice_area"]
jurisdiction["jurisdiction"]
matter["matter"]
review_cycle["review_cycle"]
score_snapshot["score_snapshot"]
end
subgraph identity["Identity and ops"]
app_user["app_user"]
session["session"]
app_setting["app_setting"]
audit_log["audit_log"]
end
question -- "1:N" --> answer_option
questionnaire -- "N:M · weight" --> question
response -- "N:1" --> questionnaire
response -- "1:N" --> response_item
response_item -- "N:1" --> question
response -- "1:N" --> response_revision
firm -- "1:N" --> office
firm -- "N:M" --> practice_area
firm -- "N:M" --> jurisdiction
matter -- "N:1" --> firm
matter -- "N:1" --> practice_area
matter -- "N:1" --> jurisdiction
review_cycle -- "1:N" --> score_snapshot
score_snapshot -- "N:1" --> firm
matter -- "N:1 · owner" --> app_user
session -- "N:1" --> app_user
%% invisible links stack the three groups vertically
engine ~~~ domain
domain ~~~ identity
classDef engineCls fill:#dcfce7,stroke:#15803d,color:#111827;
classDef domainCls fill:#dbeafe,stroke:#1d4ed8,color:#111827;
classDef idCls fill:#fef3c7,stroke:#b45309,color:#111827;
class question,answer_option,questionnaire,response,response_item,response_revision engineCls;
class firm,office,practice_area,jurisdiction,matter,review_cycle,score_snapshot domainCls;
class app_user,session,app_setting,audit_log idCls;
| Your request | Table(s) | Generalizes (spec) |
|---|---|---|
| questions | question |
criterion |
| possible answers | answer_option |
the 1–5 scale anchors |
| grouped questionnaire set | questionnaire + questionnaire_question |
evaluation form + criterion_weight |
| results with history | response + response_item + response_revision |
evaluation + evaluation_score |
The seed loads the canonical 6 criteria — 4 qualitative (1–5 scale with anchors) + 2
quantitative percent questions (0–100, normalized onto the 1–5 band for scoring) — into a
default counsel_evaluation questionnaire whose weights sum to 1.0.
Running it
Two ways to run the backend: the Docker path (everything in containers — recommended) and the local path (bare Python + your own Postgres, see Local development).
Prerequisites
- Docker path: Docker Engine + Docker Compose v2 (
docker compose ...). Nothing else needed — Postgres, migrations and the backend all run as containers. - Local path: Python 3.12 and a local PostgreSQL 16 with the
pg_trgmextension available (the full-text/fuzzy search depends on it). See Local development.
1. Configure .env (required first)
The app reads .env, not .env.example, and .env is git-ignored. Copy the template and replace every change_me_* value before starting:
cp .env.example .env
Edit .env and set at minimum:
| Variable | Why |
|---|---|
DB_SUPERUSER_PASSWORD, DB_APP_PASSWORD, DB_MIGRATOR_PASSWORD |
Postgres roles. Keep them alphanumeric — the DB init scripts interpolate them into SQL literals. |
DATABASE_URL, MIGRATION_DATABASE_URL |
Must embed the matching DB_APP_PASSWORD / DB_MIGRATOR_PASSWORD (they are duplicated, not auto-substituted). Host stays postgres for Docker. |
BOOTSTRAP_ADMIN_EMAIL, BOOTSTRAP_ADMIN_PASSWORD |
The first admin account, created by the seed step. This is your first-run login. |
The
.env.exampleplaceholders are literalchange_me_*strings — they are not auto-substituted with anything safe. If you copy the template and don't replace them, the app starts with those insecure literal values (e.g. the DB passwords staychange_me_app/change_me_migrator, the admin password stayschange_me_admin). Replace every one before starting.
2. Start the stack (fastest path)
DREDD_CORE_TOKEN=github_pat_... docker compose up -d --build
DREDD_CORE_TOKEN (read access to the private dredd-core repository) reaches only the image build, as a
BuildKit secret; no running container gets it.
Compose starts three services in dependency order, and depends_on conditions enforce it:
- postgres — comes up and must pass its
pg_isreadyhealthcheck. - migrate — a one-shot job (
restart: "no") that runsalembic upgrade head && python -m app.seed, then exits 0. A failed migration blocks everything downstream. - backend — starts only after migrate completes successfully, then runs its own healthcheck against
/api/v1/health. It is the only service published to the host: container port8000on host port80. It serves the API, the admin console and the security headers itself (there is no reverse proxy in this stack).
Postgres (5432) is expose-only — not reachable from the host. There is no TLS in this stack: for
HTTPS put your own terminator in front of port 8081 and set FORWARDED_ALLOW_IPS to its address, or run
Counsel as a module of the platform (below), where Atrium is the front door.
It's ready when the backend healthcheck passes:
docker compose ps # backend should show (healthy)
curl -s localhost:8081/api/v1/health
3. What you can open
- Admin console (UI):
http://localhost:8081/— a single static HTML/JS file served same-origin by the backend (any unknown non-API path returns it, so deep links survive a reload). - API:
http://localhost:8081/api/v1— interactive docs athttp://localhost:8081/api/v1/docs. - Liveness:
http://localhost:8081/healthz(an empty 200, no database) andhttp://localhost:8081/api/v1/health(checks the database).
Sign in with the bootstrap admin (BOOTSTRAP_ADMIN_EMAIL / BOOTSTRAP_ADMIN_PASSWORD from your .env). Served by the backend the console targets /api/v1 automatically (relative, same-origin — no CORS, nothing to configure).
4. End-to-end walkthrough
The seed already created an open review cycle (Q2 2026) and a default questionnaire (Counsel Evaluation, 6 questions — 4 qualitative scale + 2 quantitative percent), so you can go straight to creating data. Navigate with the sidebar; each list has a New … button that opens a form.
Key RBAC rule: only a
matter_ownerwho owns the matter can submit an evaluation. Whoever administers Counsel,legal_opsandviewercannot submit by design. So you set things up as the administrator, then switch to amatter_ownerto score.This walkthrough is the standalone deployment, where Counsel owns its accounts. As a module of the platform you would create the person in Atrium instead, and give them their Counsel role here (step 3 becomes Users → Edit role).
- Open
http://localhost:8081/and sign in as the bootstrap admin (admin@example.com+ your bootstrap password). - Firms (sidebar → Directory) → New firm → enter a Name, status
active→ Create firm. - Users (sidebar → Admin) → Create user → set Email, Full name, Password and Role
matter_owner→ Create user. - Matters (sidebar → Directory) → New matter → set Title, pick the Firm / Practice area / Jurisdiction, set Owner = the
matter_owneruser (the Owner selector is admin-only), choose Type/Complexity → Create matter. - Review cycles (sidebar → Review) → New cycle → set Min evaluations =
1→ Create cycle. The seededQ2 2026cycle requires 3 evaluations before a firm is ranked; a min‑1 cycle lets a single evaluation produce a ranked (non‑provisional) snapshot. - Sign out (user menu, top‑right), then sign in as the
matter_owner(their email + the password you set). - Submit evaluation (sidebar → Evaluations) → pick the
Counsel Evaluationquestionnaire (renders the Answers section), pick the matter they own, pick the min‑1 cycle you just created, optionally set Recommend?, and fill in the qualitative (scale) answers — those drive the score; the quantitative numeric fields are optional in MVP-0 and don't affect the composite → Submit evaluation. Once at least one scale answer is set, a banner rendersScore NN/100 · status · id; View history lists revisions. - Sign out and sign back in as admin.
- Review cycles → open the cycle (row menu Open) → on the cycle page click Close cycle (
POST /review-cycles/{id}/close). - The Firm rankings table loads (firm, composite score, completeness, #evals, ranking status). Closing materializes one immutable snapshot per firm with ≥1 submitted, non‑constrained evaluation, each weighted by its matter's materiality (complexity/value band).
ranking_statusfollows the composite, except a firm below the cycle's Min evals staysprovisional— which is why this walkthrough uses a min‑1 cycle. - Search: press Ctrl/⌘K (or the search icon in the topbar) and type a firm/matter name — results come from
GET /search.
5. Running the console against a bare uvicorn (local dev)
For the non-Docker path (venv, alembic upgrade head && python -m app.seed, uvicorn ... --reload --port 8000), see Local development.
The console targets its own origin by default, deriving the base from the page it was served as (/api/v1 at the origin root, /counsel/api/v1 under the platform's path prefix); a page opened from a file:// path falls back to http://localhost:8000/api/v1. When you serve the page from a different web origin than the backend (e.g. a :5500 static server while uvicorn is on :8000), it's cross-origin, so:
- Point the console at the backend by setting
localStorage.cs_base2 = 'http://localhost:8000/api/v1'in the browser console (it's validated bysanitizeBase— only a same-origin path, the same origin, or localhost is accepted), then reload. - Add the page's origin to
CORS_ALLOW_ORIGINSin.env(e.g.CORS_ALLOW_ORIGINS=http://localhost:5500,http://127.0.0.1:5500). The fetch wrapper usescredentials: 'include'+ a Bearer token, so the origin must be allowed or the request fails.
6. Troubleshooting
- Port 8081 already in use — another service holds host port 8081. The family numbers ports app / db / static per app (Galena 8012 / 8014 / 8021, Sygna 8032 / 8034 / 8041, Compass 8052 / 8054 / 8061, Counsel 8072 / 8074 / 8081) so sibling stacks don't collide; stop the other service, or change the backend's
ports:mapping (not to 8080, which is HyperDX's UI). Postgres doesn't publish to the host, so only the backend's8081can collide. - 403 when submitting an evaluation — you're signed in as someone who administers Counsel (or as
legal_ops/viewer). Only thematter_ownerwho owns the matter can submit; switch to that user. - Login fails for the bootstrap admin — the password is wrong or
change_me_*was never replaced. ConfirmBOOTSTRAP_ADMIN_EMAIL/BOOTSTRAP_ADMIN_PASSWORDin.env; the seed creates the admin idempotently from those values. - "Invalid email or password" after several tries — app-level lockout engaged. After
LOGIN_MAX_ATTEMPTS(default 5) consecutive failures the account locks forLOGIN_LOCKOUT_MINUTES(default 15). Wait it out or sign in as a different administrator. (On the platform, signing in happens at the hub and so does the lockout.) - "Sign in at the platform hub" on the sign-in screen — this deployment has
IDENTITY_SCHEMAset, so it is a module of the platform and has no password of its own. Sign in at/atrium; you arrive here already signed in. - Console requests go to the wrong host — a stale
cs_base2inlocalStoragefrom a previous bare-uvicorn session can override the derived default. Clear it (localStorage.removeItem('cs_base2')in the browser console) and reload. (The key wascs_basebefore the platform move; on a shared origin an old value is stale at best, which is why bumping the key retires it.) - Signed in but immediately signed out over plain http:// — the
Secureflag is auto-detected from the request scheme, so this should no longer happen; if it does,SESSION_COOKIE_SECURE=trueis forcing it on. Clear it (unset, not blank) or front the site with TLS. - 404 everywhere behind a path prefix, or a doubled
/counsel/counsel/—ROOT_PATHand the proxy disagree. The proxy must strip the prefix (handle_path /counsel/*) and the backend re-add it (ROOT_PATH=/counsel, which reaches both uvicorn and FastAPI); setting one without the other gives exactly these two symptoms. No trailing slash onROOT_PATH.
Configuration
All via .env (copy from .env.example; it's git-ignored). Keys you'll set:
| Variable | Purpose |
|---|---|
POSTGRES_DB, DB_SUPERUSER_PASSWORD |
Postgres bootstrap |
DB_APP_PASSWORD, DB_MIGRATOR_PASSWORD |
least-privilege role passwords |
DATABASE_URL |
runtime connection (app role, DML-only) |
MIGRATION_DATABASE_URL |
migrations + seed (migrator role, DDL) |
DB_APP_ROLE |
the runtime role the grants migration targets — the user in DATABASE_URL (app; counsel_app in the family's shared managed database) |
DB_POOL_SIZE / DB_MAX_OVERFLOW |
the backend's connection pool (defaults 5 / 10; see Deploying on a managed PostgreSQL) |
DB_LOCAL_HOSTS |
comma-separated hosts that count as local besides localhost / 127.0.0.1 / ::1 / postgres, so their URLs need no TLS (a private database on a trusted network); every other host needs sslmode=verify-full |
DB_ALLOW_UNVERIFIED_TLS |
true accepts a remote database URL without sslmode=verify-full (start-up refuses one otherwise); the one escape hatch, for a trusted private network only, never a managed provider |
APP_ENV |
production hides stack traces |
ROOT_PATH |
path prefix this deployment is mounted under — empty (default) at the origin root, /counsel as a module of the platform; pairs with the front door stripping /counsel (Atrium forwards /counsel/* without it), never set alone |
SESSION_TTL_HOURS |
session lifetime |
SESSION_COOKIE_SECURE |
force the Secure cookie flag (unset → auto: Secure only over HTTPS; never leave it assigned but blank) |
FORWARDED_ALLOW_IPS |
upstream IPs uvicorn trusts for X-Forwarded-For / X-Forwarded-Proto, so the real client IP reaches the audit log. Empty (default) = loopback only, right when nothing sits in front; the platform pins it to Counsel's network |
FRAME_ANCESTORS |
who may frame Counsel: 'none' (default, X-Frame-Options: DENY) or 'self' (SAMEORIGIN); anything else refuses start-up |
BASE_CURRENCY |
instance base currency (stored in app_setting) |
BOOTSTRAP_ADMIN_EMAIL / _PASSWORD |
first administrator, created idempotently by the seed. Standalone only: on the platform the account comes from the hub and the seed skips it |
IDENTITY_SCHEMA |
empty (default) = Counsel owns its accounts. Set (dredd) = a module of the platform: one account, one cookie, no sign-in here, and access to this module decided by a module_permission row |
SESSION_COOKIE_NAME |
the cookie's name (counsel_session; dredd_session on the platform, where all four modules read one cookie) |
MODULE_SLUG |
this module's name on the platform (counsel) — what a grant of access names, what the hub's catalogue must call this app, and what a token the hub mints for it is stamped with (counsel_pat_). Set explicitly in .env.example rather than left to the default, because a mismatch with the catalogue is silent: this app only ever reads module_permission by its own name, so a grant spelled differently never matches, nothing anywhere reports it, and the person stays locked out |
LOGIN_MAX_ATTEMPTS / LOGIN_LOCKOUT_MINUTES |
brute-force lockout (defaults 5 / 15) |
CORS_ALLOW_ORIGINS |
comma-separated origins for a separately-served admin console (empty = same-origin only) |
OTEL_ENABLED |
turn OTLP export on/off (off → backend runs standalone) |
OTEL_EXPORTER_OTLP_ENDPOINT |
collector address (http://otel-collector:4317) |
CLICKHOUSE_USER / _PASSWORD / _DB |
ClickHouse credentials for collector + HyperDX |
RBAC
Three separate questions, and keeping them separate is the point.
Whether you may open Counsel at all is the first, and on the platform it is not implied by being
signed in: one account spans four modules, so a session says who you are and nothing about where you
may go. Access is a row in the shared module_permission table naming counsel — user (may use
it) or moderator (may use and administer it) — and no row means no entry, refused once at the
edge (deps.get_current_user) rather than shown as an empty screen. Standalone there is one app and
nothing to be admitted to, so everybody with an account may use it, exactly as before.
Who administers Counsel is a platform tier, not a role in this app: an administrator
(platform-wide app_user.is_admin, who needs no row anywhere) or a moderator of counsel (this
module only). Both are granted in the hub, and this app can only read them — counsel_app holds
SELECT on that table and nothing else, so a compromised Counsel can neither admit anybody nor
promote anybody, itself included. Standalone, with no platform, the tier is simply the account's
is_admin, which the seed gives the bootstrap administrator.
What you do here is user_role on counsel_user_profile, Counsel's own side table. There used
to be an admin value in it; it was deleted (revision 0003) because the app kept the shared
app_user.is_admin in step with it — the one place in the family where a module minted a
platform-wide administrator.
Everything in the table below assumes the first question was answered yes; without a
module_permission row (or the administrator flag) none of these rows is reachable at all.
| Action | administrator / moderator | legal_ops | matter_owner | viewer |
|---|---|---|---|---|
| Manage Counsel roles | ✅ | — | — | — |
| Create / rename / deactivate accounts | in the hub | — | — | — |
| Configure questions / questionnaires / weights | ✅ | ✅ | — | — |
| CRUD firms | ✅ | ✅ | — | — |
| CRUD matters | ✅ | ✅ | own only | — |
| Submit response (evaluation) | — | — | ✅ own matter | — |
| Open / close review cycle | ✅ | ✅ | — | — |
| Read rankings / snapshots | ✅ | ✅ | own + aggregate | ✅ aggregate |
| Read audit log | ✅ | ✅ | — | — |
Whoever administers Counsel, and legal_ops, deliberately cannot submit evaluations —
separation of duties protects the independence of the matter owner's assessment, and the tier does
not lift it: it was never a limit on administration, it is what the matter-owner role means.
In Galena and Sygna a moderator projects onto a tree of nodes as manager. Counsel has no tree, so
its projection is the flat equivalent: a moderator of counsel holds every power UserRole.admin
used to hold. Same tier, same meaning, same audit row; different shape, because the two apps
authorize differently.
API reference
Base path /api/v1. Full schema at /api/v1/docs (OpenAPI).
Auth POST /auth/login · POST /auth/logout · GET /auth/me
Users GET/POST /users · PATCH /users/{id} · POST /users/{id}/deactivate
Firms GET/POST /firms · GET/PATCH /firms/{id}
Matters GET/POST /matters · GET/PATCH /matters/{id}
Dictionaries GET /practice-areas · GET /jurisdictions
Questions GET/POST /questions · GET /questions/{id}
Questionnaires GET/POST /questionnaires · GET/PATCH /questionnaires/{id}
Responses GET/POST /responses · GET /responses/{id} · GET /responses/{id}/history
Review cycles GET/POST /review-cycles · POST /review-cycles/{id}/close · GET /review-cycles/{id}/snapshots
Search GET /search?q=...&types=firm,matter,question,response
Health GET /health
List endpoints accept ?limit= (1–500, default 100) and ?offset= (default 0) for pagination.
Errors use RFC 9457 Problem Details (application/problem+json).
Scoring model
Composite score is the spec's present_i weighted mean (§F.3):
Σ (wᵢ · Cᵢ · presentᵢ)
score = ───────────────────────── × 20
Σ (wᵢ · presentᵢ)
Cᵢ— criterion value on the 1–5 scale (the cross-response average for a firm in a cycle)wᵢ— configurable weight per questionpresentᵢ— 1 if the criterion has data, else 0; re-normalizing the denominator so missing data (e.g. the quantitative criteria in MVP-0) neither imputes zero nor penalizes a firm× 20— rescales 1–5 → 0–100
Each evaluation enters the per-criterion average weighted by its matter's materiality
(ω_e = w_cx·m_cx(complexity_band) + w_val·m_val(value_band); the value axis renormalizes out
when value_band is unset — spec §F.3.1). Constrained-choice evaluations are excluded from the
ranking composite (fairness). Each closed cycle materializes one immutable score_snapshot
per firm with a full per-criterion breakdown for audit — and a firm with fewer than the
cycle's min_evaluations submitted evaluations stays provisional.
Local development
cd backend
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements.txt
# Point DATABASE_URL / MIGRATION_DATABASE_URL at a local Postgres 16 (with pg_trgm), as the
# least-privilege app / migrator roles (db/init/01-roles.sh): the grants migration refuses to run
# as a superuser or as postgres, and fails when DB_APP_ROLE (default app) names no role.
alembic upgrade head && python -m app.seed
uvicorn app.main:app --reload --port 8000
pytest # unit tests (DB-free); integration tests auto-skip without a DB
alembic upgrade head --sql # inspect the full generated DDL without a DB
Running as a module of the platform
Counsel Scorecard runs standalone at the root of its own address — that is everything above, and it
stays the default. It also runs as a module of the Dredd platform: Atrium the hub plus Galena,
Sygna and Counsel at one origin, one module per path (/atrium, /galena, /sygna,
/counsel), with / redirecting to /atrium. Nothing forks: the same image, the same console and
the same migrations serve both, and the difference is two halves of one piece of configuration.
ROOT_PATH=/counselin the backend's environment. uvicorn re-adds the prefix the proxy took off, and FastAPI emits prefixed absolute URLs; both read this one variable.- The front door strips it: Atrium's backend forwards
/counsel/*here without the prefix. This is the other half of the same decision — set either alone and you get a doubled prefix (404 everywhere) or server-generated URLs that escape the prefix. Redirect bare/counselto/counsel/(308): without the trailing slash the console's document-relative API base resolves to the platform root instead of this module.
The console needs no configuration — it derives its API base from the document it was served as. The
session cookie is already Path=/, so it travels with every path under the origin.
One account, one sign-in
Set IDENTITY_SCHEMA=dredd and this app stops having accounts of its own. app_user, session and
module_permission live in a neutral schema the hub owns and every module reads, so signing in once
at /atrium signs you in here — the browser sends the same cookie to the same origin, and this app
resolves the same session row. There is no handoff to configure: no signed assertion, no audience
binding, no second password. Set SESSION_COOKIE_NAME=dredd_session at the same time so all four
modules read one cookie; the old name keeps working for one more request so nobody is thrown out
mid-change.
What changes for this app, all of it enforced by the database rather than by a hidden menu item:
- nobody signs in here.
POST /auth/loginanswers with a sentence naming the hub, and the console shows a Sign in at the hub button instead of a password box. There is no break-glass, because a module holds noINSERTon the sharedsessiontable — a role that can write a session row can mint a credential for the administrator — so a local sign-in could not work even if it were allowed to try; - accounts are the hub's. Creating, renaming and deactivating a person happen once, in Atrium,
for every module at once. Counsel keeps the one thing that is its own: the role on
counsel_user_profile; - app tokens are listed and revoked here, minted in the hub
(
POST /api/v1/me/modules/counsel/tokens, still stampedcounsel_pat_), for the same reason; - being signed in is not being let in. Access to this module is a
module_permissionrow namingcounsel, granted in Atrium, and no row means no entry — checked once, indeps.get_current_user, for every authenticated route. Before it, a stranger with a platform account could open every screen here and merely find them empty, which is not an access decision. A module holdsSELECTon that table and noINSERT, so it can neither admit anyone nor promote anyone, least of all itself; - revision
0004merges this schema's people into the shared store, matching on lower-cased e-mail and re-pointing every row that named the local id. See it for exactly what happens to the liveadmin@example.com. Revision0005is its mirror for the standalone shape: it renames this schema's ownmodule_moderatortomodule_permissionand adds therolecolumn, for a database whose0001ran while a v0.10.x core was pinned.
Standalone is unchanged and stays the default: leave IDENTITY_SCHEMA empty and Counsel owns its
accounts, serves its own sign-in and behaves as it always has. It is the same code either way.
Note also that on one origin deps.refuse_cross_site_write no longer separates the modules
from each other (see Security).
Deploying on a managed PostgreSQL
The Dredd family (Atrium, Galena, Sygna and Counsel Scorecard) can share one managed PostgreSQL
database — one Postgres 16/17 database at a managed provider, one schema and two roles per app. The
provider hosts only the database; the backend still runs on your server with Docker Compose.
Counsel lives in its own schema counsel (never public) as the roles counsel_migrator (owns
everything, migrates) and counsel_app (DML only, append-only audit_log), isolated from the other
apps' schemas and kept out of any auto-generated API the provider offers. The same steps fit any
PostgreSQL 16/17 reached over a network.
- Do the database-wide steps once (step 0 of the runbook: TLS enforced, the provider's root CA
downloaded, any auto-generated API switched off, the connection budget sized for four apps; the
family runbook is
deploy/README.mdin the Atrium repository). - Provision Counsel once as the platform admin —
python -m dredd_core.managed provision --schema counsel --app-role counsel_app --migrator-role counsel_migrator --extension pg_trgm --identity-schema dredd --identity-owner atrium_migrator …(the last two only on the platform; they grant this app's rolesUSAGEon the shared identity schema and put it on theirsearch_path, after Counsel's own schema), or pastedb/managed/provision.sqlinto the provider's SQL editor. - Point
.envat the database (through a pooler, its session mode; userscounsel_app/counsel_migrator, as<role>.<tenant>where the pooler wants the tenant in the user name;?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt) and setDB_APP_ROLE=counsel_app— see the managed-provider block in.env.example. DREDD_CORE_TOKEN=github_pat_... docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build.- Verify with
python -m dredd_core.managed check, run as both roles inside themigratecontainer (the URLs' CA path exists only there): the loop in section 4 of the runbook.
Step by step, with the connection budget, restore and removal: db/managed/README.md.
The tooling (TLS in make_engine, the TLS rule, provision, check) comes from dredd-core ≥ v0.9.0; the shared identity schema, its tiers and the two administration tiers need ≥ v0.10.0.
Tests & CI
cd backend && pytest # unit tests (DB-free): scoring/materiality, mapper config, schemas
The integration tests (tests/test_integration.py) drive the full API loop (auth → RBAC →
matter → evaluation → scoring → cycle close → FTS) and auto-skip unless DATABASE_URL
points at a reachable, migrated Postgres. To run them locally: pip install httpx, bring up a
Postgres 16, alembic upgrade head && python -m app.seed, then pytest.
CI (.github/workflows/ci.yml, on every push / PR):
- Tests — on Postgres 16 and 17 (a matrix), creates the least-privilege
app/migratorroles, migrates + seeds asmigrator, then runs the whole suite (162 passed / 10 skipped as a standalone Counsel; the ten are the platform tests below) as the DML-onlyapprole and reports coverage (pytest-covterm-missing; reported, not gated). - Managed database — the family's shared managed database, emulated on Postgres 17 by
python -m dredd_core.managed emulate(TEST-ONLY): checksdb/managed/provision.sqlis current, provisions a decoy app and Counsel as a non-superuser admin, migrates + seeds ascounsel_migrator, runs the suite ascounsel_app, runs the managed check (schema, roles, isolation, API roles), asserts nothing landed inpublic, and cycles downgrade/upgrade. Then it does the whole thing again as a platform: a stand-in hub provisions and owns the shared identity schema, Counsel is re-provisioned as a reader of it, an account the hub has never heard of makes the cutover refuse by name, and after the import the cutover runs for real —tests/test_platform_live.pythen proves that asessionrow written by the hub signs you in here, andmanaged check --identity-tier readermeasures the grants rather than trusting them. - License gate —
pip-licensesfails the build on any GPL/AGPL/SSPL dependency (LGPL is allowed by policy, though the stack no longer ships any), satisfying the spec's gate-clean requirement.
Project layout
.
├── README.md · CREDITS.md · CLAUDE.md · SHOWCASE.md docs · credits/licenses · guidance · screenshots
├── docker-compose.yml app stack (postgres · migrate · backend on :8081)
├── docker-compose.managed-db.yml override for a managed PostgreSQL database (no local postgres)
├── .env.example · .gitattributes config template · LF normalization
├── .github/workflows/ci.yml Postgres 16/17 tests · managed-database job · license gate
├── netlify.toml Netlify build for the live demo
├── scripts/build_demo.py builds the live demo (index.html + mock API + social-preview meta)
├── frontend/index.html static admin console (Open Mercato-inspired UI)
├── assets/ app icon (icon.svg + icon.png) + og.png social card
├── gallery/ screenshots (referenced by SHOWCASE.md)
├── db/init/ extensions + least-privilege roles (run as superuser)
├── db/managed/ managed PostgreSQL: provision.sql (rendered) + runbook
├── observability/ otel-collector-config.yaml
└── backend/
├── Dockerfile · requirements.txt · pyproject.toml · alembic.ini
├── alembic/ env + migrations (0001 enums/tables/FTS, 0002 runtime grants)
├── scripts/license_gate.py CI license check (deny GPL/AGPL/SSPL)
├── tests/ unit (DB-free) + integration (Postgres)
└── app/
├── main.py config.py db.py deps.py errors.py security.py observability.py
├── enums.py schemas.py seed.py logging_config.py
├── models/ ORM entities (identity, reference, firm, matter, review, questionnaire)
├── services/ auth, responses, scoring, search, audit
└── routers/ auth, users, firms, matters, questions, questionnaires,
responses, review_cycles, search, dictionaries, health
Scope & roadmap
- In this build (MVP-0): questionnaire engine, RBAC + login lockout, Postgres FTS,
present_iscoring with materiality weighting +min_evaluationsgating, review cycles + immutable snapshots, append-only audit, OTel→ClickHouse→HyperDX observability, a static test console, and CI (Postgres tests + license gate). - Modeled but not built (roadmap): invoice import (CSV/PDF) and the 3 quantitative
criteria, multi-currency with frozen FX, recency weighting, SSO/OIDC, AI scrutiny. The
scoring formula already tolerates their absence via
present_ire-normalization.
Security
- Secrets only in
.env(git-ignored); passwords hashed with Argon2id. - Postgres uses
expose, neverports; the backend is the only host-published service. - The backend sets the security headers itself on every response (API, console, errors):
X-Content-Type-Options: nosniff,Referrer-Policy: same-origin, a CSP withframe-ancestorsfromFRAME_ANCESTORSand the matchingX-Frame-Options, HSTS on HTTPS requests only, noServerheader; request bodies are capped at 100 MB. - Server-side sessions (
sessiontable) → logout / deactivate revokes access instantly. - The session cookie is
Path=/,HttpOnly,SameSite=Lax, withSecureauto-detected from the request scheme and noDomain. - Cookie-authenticated writes (login and logout included) must come from this origin: a
Sec-Fetch-Site/Origincheck refuses a same-site sibling subdomain, whichSameSitealone does not stop. Bearer-token calls andCORS_ALLOW_ORIGINSentries are trusted — so never list a sibling module's address there. On one origin this check no longer separates the platform's modules from each other; it still blocks genuinely foreign sites. - App-level login lockout after
LOGIN_MAX_ATTEMPTSfailures; client IPs are validated before being stored in theINETaudit columns. appDB role is DML-only and append-only onaudit_log; DDL is isolated tomigrator. The grants migration refuses to run as a superuser orpostgresand fails loudly when a grant does not take.- On a managed Postgres every connection is
sslmode=verify-fullagainst the provider's CA (sslmode=prefer/allow/disableare refused), and the migrator's credentials never reach the long-running backend. - Real client IPs: uvicorn honors
X-Forwarded-Foronly fromFORWARDED_ALLOW_IPS. Standalone nothing sits in front, so it is empty (loopback only) and the peer address is the client's. Behind a proxy (yours, or Atrium on the platform, which pins Counsel's network), list exactly that hop, never*, and with several hops (CDN/LB) keep the list spanning every one, or the recorded IP will be the nearest proxy instead of the client. - For production: terminate TLS in front of the backend (or run on the platform) and rate-limit
/authat that hop, per spec §K.
License
Apache-2.0 — see LICENSE and NOTICE. Chosen over MIT/AGPL
for its explicit patent grant and clean acceptance in corporate legal/IT review (spec §D).