Files
adminandClaude Opus 5.5 16f670aa7c Publish the standalone console on :8041, the family's port for this app
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>
2026-10-16 18:03:51 +02:00

25 KiB
Raw Permalink Blame History

Sygna

System zarządzania kancelarią — practice management for Polish law firms: clients, matters, parties, conflict checking, deadlines and time recording. Self-hosted, Apache-2.0, no copyleft dependencies.

Sygna is the sibling of Galena, a git-backed cloud drive. Sygna owns matters, people, time and money; Galena owns documents and their history. A matter's case file (akta sprawy) is a Galena project, referenced by matter.document_node_id — neither application duplicates the other.

Status: Stage A / Phase 1. See PLAN.md for the roadmap and the compatibility contract with Galena, and docs/CRMecenas-Discovery-Report.md for the research behind it.


Why not a generic CRM

A generic CRM models lead → deal → close. A law firm models client → matter → work → bill, and the matter outlives the deal by a decade. Three things make this a vertical product rather than a Salesforce configuration:

Conflict of interest checking is a blocking gate. Before a matter can be opened, Sygna searches every client, former client, opposing party and related entity — with matching that copes with Polish declension (Kowalski / Kowalskiego / Kowalskiemu), folded diacritics (Łódź = Lodz) and legal-form noise (sp. z o.o. = S.A. = nothing) — and refuses to open the matter until a human records a decision with a reason. That record can never be edited or deleted afterwards; the database enforces the second half. One check opens one matter, so a clear result from last month cannot be reused when the facts have changed.

Deadlines are existential. A missed termin zawity is malpractice, so a statutory or court deadline is not "managed" until a second person has confirmed it — and confirm refuses the person who entered it. Derived deadlines record how the date was reached in words (doręczenie 2026-08-03 + 14 dni) and point back at the correspondence that started the clock. That link is enforced, not decorative: a service date can be corrected until a deadline depends on it and is refused afterwards, and correspondence with derived deadlines cannot be deleted. A deadline that has lost the document proving where its date came from is worse than a blocked delete.

Ethical walls are deny-by-default for named individuals. Role-based access cannot express "everyone in the department except Anna", which is what an information barrier is. A deny removes every role on that matter — owner, manager and instance administrator included — and the matter returns 404, not 403, because its existence is itself privileged. Walls are administered from outside the barrier, so walling yourself off is never a one-way door.


Quick start

Docker (the whole stack)

cp .env.example .env    # then edit the passwords
docker compose up -d --build

Postgres → migrate (+seed) → backend on :8041 (the family numbers ports app / db / static per app — Sygna 8032 / 8034 / 8041 — so sibling stacks run side by side). There is no reverse proxy: the backend serves the API, the console and its own security headers, and is the only published service; the database is expose-only. For HTTPS put your own TLS terminator in front (and set FORWARDED_ALLOW_IPS to its address), or run Sygna as a module of the platform, where Atrium is the front door. FRAME_ANCESTORS ('none' by default, or 'self') decides who may frame the console. Sign in with BOOTSTRAP_ADMIN_EMAIL / BOOTSTRAP_ADMIN_PASSWORD.

Deploying on a managed PostgreSQL provider

The family — Atrium as the hub, Galena, Sygna and Counsel Scorecard as its modules — can share one managed PostgreSQL database (Postgres 16/17 at a managed provider). The provider hosts only the database; the backend still runs with Docker Compose on your own server. Sygna lives in its own schema sygna, with its own roles sygna_migrator / sygna_app, and holds nothing in any other app's schema; a provider's auto-generated API roles get nothing in it.

python -m dredd_core.managed provision ...   # once, as the platform admin: schema + roles (db/managed/README.md)
DREDD_CORE_TOKEN=... docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
  • Database-wide steps (creating the database, the provider's root CA, any auto-generated API off, TLS enforcement, network restrictions, the connection budget, backups and provider restores): the checklist at the top of db/managed/README.md, once for all four apps; the family runbook in Atrium's repository (deploy/README.md) covers it in more depth.
  • Sygna's steps (provisioning, .env, migrate and seed, the managed check, restore): db/managed/README.md.
  • Connect with sslmode=verify-full (through a pooler, its session mode, never transaction mode; <role>.<tenant> user names where the pooler wants them); set DB_APP_ROLE=sygna_app and size DB_POOL_SIZE / DB_MAX_OVERFLOW to the shared connection limit. Sygna's settings refuse a URL for a host that is not local without verify-full before anything connects, and python backend/scripts/deploy_check.py --env .env checks all of the above before you start.
  • The long-running backend gets no migrator credentials there, so a restore runs as the one-shot python -m app.restore (or opt in to the console's restore — the runbook says what that costs).

Netlify (the console only, and a demo)

netlify.toml publishes frontend/ as a static site — the same arrangement Galena uses. It is a front door, not a deployment: the backend is FastAPI + PostgreSQL with two in-process schedulers and cannot run on a static host. Point SYGNA_BACKEND_URL at a backend running the Docker way above and Netlify proxies /api/v1/* and /healthz to it. Also list the site in that backend's CORS_ALLOW_ORIGINS (https://<your-site>.netlify.app): Netlify's proxy replaces Host with the backend's, so the console's Origin no longer matches it, and without that entry the cross-site write guard refuses login and every cookie write (403).

With no backend configured, the build injects frontend/demo.js: the console then runs entirely in the browser against an invented Warsaw firm — three matters, a wall, an overdue deadline, an unpaid invoice — with the data in localStorage and nothing leaving the page. That is what makes the URL something you can send to somebody. SYGNA_DEMO=0 opts out.

A real firm keeps the console on the same origin as its API, served by its own backend: everything here is privileged material, and a proxy in front of it is one more place that sees it.

Local development

You need PostgreSQL 16 (17 works too — it is what managed providers commonly run) and Python 3.12.

cd backend && python -m venv .venv && .venv/bin/pip install -r requirements-dev.txt

Create the least-privilege roles (this is what db/init/01-roles.sh does in Docker):

psql -U postgres -d sygna -v ON_ERROR_STOP=1 -c "CREATE ROLE migrator LOGIN PASSWORD 'migpw'; CREATE ROLE app LOGIN PASSWORD 'apppw'; GRANT CONNECT ON DATABASE sygna TO migrator, app; ALTER SCHEMA public OWNER TO migrator; GRANT USAGE ON SCHEMA public TO app; CREATE EXTENSION IF NOT EXISTS pgcrypto;"

Then, with DATABASE_URL and MIGRATION_DATABASE_URL pointing at it:

cd backend && alembic upgrade head && python -m app.seed
cd backend && .venv/bin/python -m uvicorn app.main:app --port 8032 --app-dir .

The console is served by the backend at http://localhost:8032 (in production too: the backend is its own edge, with the SPA fallback and the security headers). On Windows write .env without a BOM — see the gotchas in CLAUDE.md.

SEED_DEMO=true creates a small firm whose demo data is chosen to exercise the conflict engine: Nowak Transport sp. z o.o. is a client in one matter and the opposing party in another, so the first conflict search a new user runs returns a real hit rather than an empty screen.

Tests

cd backend && pytest                        # DB-free; integration auto-skips
SYGNA_RUN_INTEGRATION=1 pytest              # full API loop against a migrated + seeded Postgres
python scripts/license_gate.py              # deny GPL/AGPL/SSPL

Architecture

Stack FastAPI · SQLAlchemy 2 · Alembic · PostgreSQL 16 or 17 (pg8000, pure-Python) · Argon2id · server-side cookie sessions · vanilla-JS console with no build step
Layering routers → services → models, enforced by convention. Routers never build SQL; services/authz.py is the only access authority.
Tree workspace (kancelaria) → group/folder (dział, zespół) → matter. A matter is a leaf, mirroring Galena's project rule. Roles viewer < editor < approver < manager inherit down the tree; the highest ancestor-or-self grant wins.
Least privilege migrator owns DDL; the runtime app role is DML-only, cannot mutate audit_log, and cannot delete conflict_check.
Money & time Integer grosze and integer minutes. Time rounds up to 6-minute units; the amount rounds down, in the client's favour. Court fees round up to a whole złoty — art. 21 u.k.s.c., not a preference.
Rates Effective-dated cards scoped to a matter, a client or the firm. Resolution reports its own source; recorded time keeps a rate snapshot, so editing a card never re-prices the past.
Integrations All external I/O is behind app/integrations/, with bounded retries and a single UpstreamError. A connector failure never breaks the primary action.
License Apache-2.0. CI gate fails the build on any GPL/AGPL/SSPL dependency.

Galena integration

Set GALENA_BASE_URL and each new matter gets a Galena project as its case file. Calls carry the acting user's token, never a service account, so Galena's authorization stays the single authority on document access and there is no privilege-escalation seam between the two applications. Leave it empty and the integration is a clean no-op: matters are created without a case file and the console says so.

Sygna and Galena are two modules of one platform, served at one origin under /sygna and /galena. Set IDENTITY_SCHEMA and they share one identity store: app_user, session and module_permission live in a neutral dredd schema owned by the hub's migrator — one row per human, plus one row per person per module they may open. Because sessions are already DB-backed with hashed tokens and the family is one origin, a shared session table is single sign-on — one cookie, no new protocol, no cross-origin handoff to design, and nothing here should ever grow one. One account is not one key to everything, though: module_permission says which modules a person may use and which they administer, no row means no access, and it is granted in the hub. The user's separate Galena token goes with it: the token the caller already holds resolves in Galena, so there is nothing to mint, paste, encrypt or re-enter. Everything else stays as isolated as it is today — Sygna keeps its own schema and its own least-privilege roles, and its role holds no write of any kind on the shared accounts or on who may reach it.

Leave IDENTITY_SCHEMA empty and Sygna is a standalone application that owns its own accounts and signs its own people in, exactly as before. That is a supported deployment, not a legacy one, and it runs the same code — which is why each user then still stores a Galena token: two independently deployed applications genuinely have two identity stores. See PLAN.md §3.4 and SHARED.md.


Roadmap

Phase 1 — the spine. (done) Clients, matters, typed parties, conflict checking, deadlines, time recording, per-matter access with ethical walls, immutable audit log, Polish console.

Phase 1½ — the correspondence spine. (done) An inbox where every incoming document lands unassigned, a service date established by hand, and deadlines derived from it with full provenance. Built before the connectors on purpose: the hard part was never fetching a document, it was deciding what a service date means. Items from e-Doręczenia and the Portal Informacyjny that have no service date yet get their own count on the pulpit — each one is a clock that may already be running while nobody is watching it.

Phase 1¾ — money groundwork. (done) A court-fee calculator (opłata sądowa, koszty zastępstwa procesowego, opłata skarbowa) whose schedules are held as auditable data with the statute on every bracket — and which states its own version and tells you to verify, because a calculator that looks authoritative and is out of date is worse than one that admits it. Plus rate cards: effective-dated and scoped, resolved matter override → matter card → client card → firm card → house setting, and within a card person → grade → fallback. The resolver reports where the rate came from, because the first question about any invoice line is "why 520 and not 450". Rates resolve for the date of the work, and recorded time keeps its snapshot.

Phase 1½+ — reminders. (done) A deadline system that needs you to remember to look at it is not a deadline system, so the engine now tells people: milestones at 14/7/3/1/0 days, an overdue notice once, and an escalation after three days to whoever manages the matter — falling back to the owner in a solo practice. It also chases the two things that quietly rot: incoming post with no service date, and conflict checks nobody has decided.

Every reminder carries a dedupe key enforced by a database constraint, so the scheduler can run as often as it likes and POST /admin/reminders/run is safe to press at any time. Ethical walls apply to notifications too — a wall a notification leaks through is not a wall.

Reminders that leave the building. (done) The engine wrote notifications; now they reach people. One message per recipient per sweep rather than one per notification, delivery tracked on the row itself so the scheduler stays safe to run as often as it likes, and a failed send retried rather than lost — a mail server being briefly down must never swallow a deadline warning.

What the message may say is a confidentiality decision, not a formatting one. By default it names no client, no matter and no deadline: just how many notices are waiting, and a link. Mail leaves the firm, and tajemnica adwokacka does not stop at the SMTP boundary. A firm running its own mail server can switch on full detail; the console says plainly what that means. SMTP is stdlib-only — no dependency, no licence-gate entry — and an unconfigured instance is a clean no-op that says so.

Phase 1⅞ — public registers. (done) Look a company up by KRS and its record fills itself in — name, legal form, NIP, REGON, address, and the e-Doręczenia (BAE) address, which is Phase 2 groundwork arriving early. Biała lista gives VAT status and the registered bank accounts, so a counterparty's account can be checked before money leaves the client account. A register fills blanks and never overwrites what the firm deliberately recorded.

The honest limit: the KRS API masks the names of natural persons — a board member comes back as N**********. Sygna reports how many officers there are and what they do, says plainly that the names are redacted, and asks you to enter them by hand. Inventing a party from a masked name would put a fiction into the register that decides whether the firm may take a case.

Phase 3 — money. (done) Disbursements that know a recharged court fee carries no VAT of yours; invoices that go draft → approved → issued, where approval records who read the narratives the client is about to read; a number assigned only at issue, because a gap in the sequence is a question from the tax office; and an issued invoice that can only be corrected by a credit note, which mirrors it and hands the work back to unbilled so it can be re-billed rather than quietly written off. Client money sits on its own ledger with a balance that cannot go negative — a database constraint, not a good intention.

And the numbers partners ask for: realisation (how much of the work's nominal value survived to an invoice, and how much of that turned into cash — net of VAT, because VAT is not revenue), utilisation measured against real Polish working days with the public holidays computed properly, matter profitability, lock-up (how many days a złoty of work waits to become cash) and an aged-debt table. Every one of them filtered through the same permission resolver as everything else — a management report that quietly includes a walled matter is a leak wearing a spreadsheet. A matter whose time has no cost rate behind it reports incomplete rather than a flattering margin computed from zeroes.

Finding things. (done) One box — Ctrl+K, or / — over matters, parties, correspondence, deadlines, invoices and inquiries. It folds Polish diacritics in SQL, so lodz finds Łódź and a keyboard whose Polish layout is off still finds Zażalenie; it matches parties by alias and by NIP typed without the separators; and it finds a matter by its client's name, because "the Nowak case" is what people actually type. Every result and every count is filtered through the same permission resolver as the rest of the application.

Operations. (done) One .tar.gz holds the whole instance — every table plus everything under DATA_DIR — and a restore puts it back atomically. Storage is the source of truth: names carry a UTC timestamp so listing and pruning never open a file. The dump is pure Python rather than pg_dump, because depending on a client binary makes restores fail exactly when they matter. Archives never contain .env, so a leaked archive is not also a credential leak. Off by default — and the console says plainly that at self-hosting, that risk is the firm's to carry.

Pisma procesowe. (done) Pełnomocnictwo, wezwanie do zapłaty and pozew o zapłatę, filled from the matter and downloaded as .docx — editable, because a pleading is edited before it is filed and a PDF would be a retyping job. Each template names the provision it exists for, the same rule as the fee schedules: a lawyer can check the boilerplate against a statute without reading Python.

The hard part is Polish. Przeciwko Jan Kowalski tells a judge the software filled in a blank, so every name is declined — Janowi Kowalskiemu, Piotra Zielińskiego, Anny Kowalskiej — and the rules that matter most are the ones about not declining: a woman's consonant-ending surname does not move (Annie Nowak), and a registered company name never moves at all, because the legal form carries the case and the name must match the KRS entry character for character. Where the engine does not recognise a pattern it leaves the nominative and says so, above the download button. A document that looks finished and is wrong where a court reads carefully is worse than one with a visible gap.

The month view. (done) Deadlines and hearings on a calendar that knows which days are not working days — public holidays computed, Easter included. The reason it exists rather than being a nicer list: a termin falling on a Saturday or on Boże Ciało is not due that day. Art. 115 k.c. moves it to the next working day, and a calendar that draws it on the holiday and says nothing has hidden the one fact the reader needed. So each such deadline says when it actually expires — and the stored date does not move, because that date was derived from a service date and confirmed by a second person.

Seven columns of CSS grid and a JSON payload: PLAN.md flagged the month view as the place the no-build console constraint would finally bite, and it turned out not to. On a phone the grid becomes a list of the days that have something on them, which is what you look at on a phone anyway.

The invoice as a document. (done) Phase 3 modelled the money; this is the thing a firm actually sends. A faktura (and a faktura korygująca) as .docx, with the line table, the net and VAT split per rate as art. 106e ust. 1 pkt 13–14 requires, recharged court fees shown at 0% with a note saying why, payment terms and the bank account. The required elements are held as data with the provision on each, and a test asserts they reach the page — so the statute is checked against the output rather than against anyone's memory.

Kwota słownie, because every Polish invoice carries it and a figure that has been altered no longer matches its own words. That means three plural forms applied to numerals, scale words and the currency alike: jeden złoty, dwa złote, pięć złotych, dwa tysiące, dwadzieścia jeden tysięcy. A missing seller NIP is reported as a warning, never printed as a blank — an invoice without one is not a valid invoice, and a gap on the page would hide that.

The firm's own templates, and the case file. (done) Upload a .docx with your letterhead and house wording, put {klient_dop} where a name goes, and it fills from the matter with the same declension the built-in pisma use. The hard part is that Word does not keep a placeholder in one piece — {klient_dop} can sit across three runs — so substitution happens across a whole paragraph rather than run by run. Headers and footers are filled too, because that is where letterhead lives. An unknown placeholder is left visible rather than blanked: a silent hole in a document is worse than an obvious one.

And a generated document — pleading or invoice — can go straight into the matter's case file in Galena, through Galena's own API and with the acting user's token, so it arrives with a commit, an author and a diff. That is the whole reason the case file lives in Galena rather than in a folder here. Filing is best-effort and always reported: the document is produced either way, and you need to know when it is not in the file rather than assume it is.

AML / KYC. (done) A law firm is an instytucja obowiązana only for the activities in art. 2 ust. 1 pkt 14, so an assessment belongs to a matter rather than to a client — and recording "out of scope, because…" is itself the answer an inspection wants. Risk factors are data with the provision on each, scored into simplified / standard / enhanced measures, and the rating comes back with its reasons so it can still be defended two years later. PEP is an override rather than a heavy factor: art. 46 requires enhanced measures regardless of what else is true.

The assessment is evidence. It is never edited after approval — a change of circumstances produces a new one that supersedes it — and the runtime database role has no DELETE on it, because a firm that can quietly remove its own due-diligence record does not have one. Sign-off is refused if nobody wrote down what was actually done.

What it will never do is file a report. Art. 2 ust. 2 carves out what a lawyer learns while ascertaining a client's legal position, which is most of what a firm knows. Software that nudged a lawyer towards sending privileged material to a state authority would be actively dangerous, and an automated one worse. Sygna records that a human decided; the privilege analysis stays with the lawyer.

Phase 2 — the Polish moat. The feed. e-Doręczenia (UA API v3 + BAE — v1/v2 were switched off on 1 Jan 2026) writes through the same services/correspondence.record the console uses, so the connector inherits the service-date and idempotency rules instead of re-implementing them. Then KSeF 2.0, then KRS / CEIDG / Biała lista for party auto-fill. Request the e-Doręczenia test environment before writing any of it — the queue, not the code, is the schedule risk.

Phase 3 — money. Rate cards, pro-forma review, invoices with KSeF, disbursements, client deposits, and the reports partners ask for: WIP, realisation, utilisation, lock-up.

Phase 4 — the wedge. Portal Informacyjny sync. Hardest integration, highest switching cost, and tied to filing via PI becoming obligatory for adwokaci/radcowie on 1 March 2027.

Phase 5 — depth. Document generation with Polish declension, PAdES signing via a QTSP, the AML/KYC module, a client portal, court-fee and koszty zastępstwa calculators, and the platform convergence with Galena — one account, and the case file embedded rather than linked.


Confidentiality

Tajemnica adwokacka is a stronger regime than RODO and both apply at once, so the constraints are architectural rather than policy documents: self-hosted by default (the operator chooses where the data lives), an append-only audit log recording who opened which client's file, and government APIs as the only outbound traffic — all of it behind one boundary that logs what it sends. Any future AI feature must be EU-hosted inference with contractual no-training terms, switchable off per matter, and off by default.

License

Apache-2.0. See LICENSE.