Caddy is gone from the platform and the standalone stacks; the backend is its own edge (and Atrium's backend the platform's front door). Comments, docstrings and current docs now describe that instead of naming Caddy; leftover config lines (.gitattributes, CREDITS rows) go; dated records are marked historical. Test names lose "Caddy" (CADDY_*_CSP -> PINNED_*_CSP); no assertion changes, and the "no Caddy" guards stay. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
49 KiB
Sygna — Build Plan
Sygna — a practice-management system (CRM + matters + time + billing) for Polish law firms. Sibling application to Galena; designed from day one to merge into one shared system with it.
- License: Apache-2.0 (same as Galena). Permissive-only dependency policy, enforced in CI.
- Stack: identical to Galena — FastAPI + SQLAlchemy 2 + Alembic + PostgreSQL 16, Argon2id +
server-side cookie sessions, a no-build static console (vanilla JS), Docker Compose; the backend
is its own edge (
app/edge.py), with no reverse proxy. - Supersedes: §4 of
docs/CRMecenas-Discovery-Report.md. The discovery report's requirements analysis (§3) still stands; its technology recommendation (Atomic CRM / react-admin / a hosted Postgres BaaS) is withdrawn — see §1.2.
1. Requirements analysis
1.1 What was asked
| # | Requirement | Resolution |
|---|---|---|
| 1 | Name it Sygna | Locked. From sygnatura akt — the case reference number, which is literally the primary key of a legal matter. §1.4 covers the brand surface. |
| 2 | Use the same tech stack as Galena | Locked. §2 pins it version-for-version. |
| 3 | Make it compatible with Galena for a future shared system | This is the design driver, not a footnote. §3 is the compatibility contract; it changes the data model, the auth model and the UI shell. |
| 4 | Produce PLAN.md | This document. |
| — | License: Apache-2.0 | Locked. LICENSE written. CI gate denies GPL/AGPL/SSPL, matching Galena's policy. |
1.2 What this changes versus the discovery report
The report recommended forking Atomic CRM (MIT, React + a hosted Postgres BaaS). Requirement 2 overrides that — and on inspection the override is an improvement, not a compromise:
- Galena already is the better starting point. It is Apache-2.0, already ours, and already
implements the half of a legal system that is expensive to build: versioned document storage, a
review/approval workflow, encryption, an audit log, a permission tree with inheritance, an in-browser
document viewer (PDF/DOCX/scans), OCR, and side-by-side comparison with authorship. In legal terms
that is the case file (
akta sprawy) — done. - What Sygna adds is what Galena deliberately does not do: clients, matters, parties, conflicts, deadlines, time, money, and the Polish statutory integrations.
- Two dependencies from the report are dropped. Mayan EDMS (document management) is unnecessary —
Galena is the DMS. docassemble (MIT, document assembly) is deferred from v1: it is an entire
second stack (its own Python app, Redis, Celery, Apache) and would violate requirement 2. Document
generation in v1 is
python-docx(already a Galena dependency) + a template merge with Polish declension; docassemble stays a documented optional sidecar for v3. - The frontend constraint is real and accepted. No React, no TypeScript, no build step for the
console. Galena proves this scales further than it sounds — its
app.jsalready carries an editable CSV grid, a commit-graph renderer, a diff viewer and a full i18n layer. Where a component genuinely needs a build (a month-view calendar), Sygna follows Galena'sfrontend/static/editor.jsprecedent: a Vite bundle built separately and committed as a static artifact, with a working fallback if it is absent.
1.3 The three things that make this a vertical product
Everything else is table stakes. These are the reasons a firm buys Sygna instead of a generic CRM, and they get the architectural attention:
- Conflict of interest checking — a blocking gate at intake, fuzzy across Polish declension and diacritics, searching clients, former clients, opposing parties and related entities, producing a permanent decision record. Professional-liability grade.
- The deadline engine —
terminycomputed from a legally binding service date, with dual confirmation and escalating reminders. A missedtermin zawityis malpractice. - The Polish statutory integrations — e-Doręczenia, Portal Informacyjny, KSeF. Dated, mandatory, and effectively impossible for an international vendor to ship quickly.
1.4 Brand surface
Following Galena's invariant — UI chrome is monochrome; the brand colour appears only on the app
icon (Galena: Open Color violet8 #5f3dc4 on violet0).
- Sygna's mark: Open Color
cyan8#0c8599 rounded square, glyph incyan0#e3fafc — visually distinct from Galena's violet at launcher size, which matters once both apps sit in one shell. Glyph: a section mark / reference-number motif rather than a scales-of-justice cliché. (An earlier draft of this file called #0b7285 "teal8". It is actuallycyan9; realteal8is #099268. The palette is cyan throughout.) - Where the brand appears: the app mark, icon tiles, the avatar and the focus ring — things that read as an identity. Buttons, nav and toolbar glyphs stay monochrome; a console where everything is branded has nothing that stands out.
- Chart colours reuse Galena's
--chart-1/2/3tokens verbatim (violet/teal/orange, per-theme). - Wordmark: "Sygna". Tagline: system zarządzania kancelarią.
- Not yet done:
.pl/.comdomain and UPRP/EUIPO clearance for "Sygna". Do this before any public branding; the name is otherwise unverified.
2. Stack — pinned to Galena
Identical choices, identical versions, so a future merge has no dependency reconciliation.
Backend
Python 3.12+ ruff, line-length 100, target py312
fastapi==0.115.6 API_PREFIX = "/api/v1"; docs at /api/v1/docs
uvicorn[standard]==0.34.0
python-multipart==0.0.20 multipart uploads
pydantic==2.10.4 + pydantic-settings==2.7.1 (typed Settings from .env)
SQLAlchemy==2.0.50 Mapped[]/mapped_column style, DeclarativeBase
alembic==1.14.0
pg8000==1.31.2 pure-Python PostgreSQL driver, BSD-3 (no libpq, no LGPL)
argon2-cffi==23.1.0 Argon2id password hashing
cryptography==44.0.0 AES-256-GCM, if/when Sygna stores secrets at rest
New dependencies Sygna needs (all permissive, all pass the gate):
httpx BSD-3 — the one outbound HTTP client, for every government API
signxml Apache-2.0 — XAdES signing for KSeF (verify against KSeF 2.0 spec)
pyHanko MIT — PAdES signing/verification for PDF pleadings (Phase 4)
python-docx==1.1.2 MIT — already a Galena dep; template merge for document generation
Pillow==11.1.0 HPND — already a Galena dep; if Sygna renders anything
Deliberately not added: Celery/Redis (use an asyncio task in the app lifespan, exactly as
Galena's backup scheduler), an ORM-adjacent admin framework, any Node backend.
Frontend
Vanilla JS, no build. index.html + app.css + app.js, hash router, the api()/esc()/toast()
helpers, the ICN icon map, the theme pre-paint inline script, EN/PL i18n by English-source-text
matching (I18N.pl + _tr/_trAttr/localize, covering title and placeholder attributes).
Sygna is PL-first, so the English source strings must be short and stable, and PL coverage is a
merge requirement, not a follow-up.
Infrastructure
docker-compose.yml postgres:16 → migrate(+seed) → backend (only the backend published)
db/init/01-roles.sh creates the least-privilege `app` and `migrator` roles
backend/app/edge.py the backend's own edge: static console, security headers, gzip, body cap
.github/workflows pytest (+ coverage) on a Postgres service, then scripts/license_gate.py
Dev ports (offset from Galena's 8012/8014/8021 so both can run side by side):
.claude/launch.json → sygna 8032, sygna-db 8034, sygna-static 8041.
Env prefix SYGNA_* (SYGNA_FRONTEND_DIR, SYGNA_RUN_INTEGRATION); unprefixed DATABASE_URL /
MIGRATION_DATABASE_URL / DATA_DIR as in Galena.
3. Compatibility contract with Galena
The goal: one system, two applications, one identity, one permission tree, one design language. Sygna is the system of record for matters, people, time and money; Galena is the system of record for documents and their history. Neither duplicates the other.
3.1 The central mapping
A matter is to Sygna what a project is to Galena.
Galena's org tree is workspace → group/folder → project, where a project is a leaf and its
contents live in git. Sygna reuses that tree verbatim — same node table, same permission_grant,
same materialized path, same authz resolver — and adds matter as a second leaf kind.
Each matter owns a Galena project as its case file:
matter.document_node_id → node.id (kind = 'project')
The project is created automatically when a matter is opened, as a sibling of the matter node under the same parent container. Consequences:
- Galena's invariant "a project is a leaf; nothing nests inside it" is untouched — no change to Galena is required to make this work.
- A single
permission_granton the parent container covers both the matter data and its documents, so access stays coherent without a second permission system. - Opening
Sprawa → Aktadeep-links to Galena at#/n/<document_node_id>(Stage A) or embeds Galena's ReaderJS viewer same-origin (Stage C).
Alternative considered: relaxing Galena's leaf rule so a project can nest inside a matter node. Cleaner conceptually, but it edits Galena's most load-bearing invariant to buy nothing. Rejected.
3.2 What core owns (was: what is copied verbatim)
This section used to list files that had to stay byte-identical with Galena so Stage B would be a
data move rather than a rewrite, with a divergence rule: change both repositories in the same
commit. That regime is over. Those files are dredd-core, imported and pinned by tag, so there
is one copy and "which version" is a line in requirements.txt rather than a property of two
working trees a script has to go and measure.
From dredd_core |
Was |
|---|---|
Base, UUIDPkMixin, TimestampMixin, NAMING_CONVENTION |
models/base.py, copied |
AppUser, Session, AppSetting, AuditLog |
models/identity.py, copied |
Node, PermissionGrant, Favorite |
models/node.py, copied |
authz — resolver, grant CRUD, readable_node_ids |
services/authz.py, copied + forked for walls |
auth.AuthService / AuthPolicy |
services/auth.py, copied |
security, audit, db, errors, schema |
copied, one file each |
UUID primary keys still matter for the same reason they always did — ids unique across every application's database — even though there is no longer a merge to prepare for.
What is still copied, because none of it is importable code: alembic/env.py,
db/init/01-roles.sh, scripts/license_gate.py, and the console shell (api(), esc(), ICN,
the theme handling, app.css tokens). SHARED.md lists the first three and shared_check.py still
guards them. The console shell is a fourth, and nothing checks it — a JavaScript package for the
family is the obvious next extraction, and it does not exist.
3.3 Enum compatibility
NodeRole (viewer < editor < approver < manager) comes from core unchanged — the ranking maps
onto legal practice cleanly:
| Role | In Sygna |
|---|---|
viewer |
read the matter and its file; no time entry |
editor |
record time, add parties, draft documents, create deadlines |
approver |
approve invoices, sign off conflict checks, publish pleadings |
manager |
manage access on this node and below |
NodeKind is no longer an enum at all. Core stores node.kind as text validated against each
application's registry (services/nodes.node_kinds()), so Sygna contributes matter with no core
change and no migration — the whole point of the registry. NodeKind survives in enums.py as a
constants holder so the comparisons throughout the codebase read the same; because a StrEnum
compares equal to its own string they work against a text column, but reads must not take
.value.
PrincipalType, ReviewPolicy and EncryptionMode come from core. Every Sygna-specific enum
(§4.1) is a native PG enum mirrored as a StrEnum — and is no longer registered anywhere by hand:
dredd_core.schema.create_enum_types derives the labels from the metadata, so the migration's old
ENUMS map is gone and adding an enum needs no migration edit.
3.4 Superseded: the staged convergence
Superseded 2026-09-23 — and the supersession recorded below was itself wrong. Everything in this section is 2026-09-12's reading, in which "separate applications sharing a package" became the architecture. It is not the architecture.
One platform, one account, one admin pane. The family runs at one origin, one module per path (
/atrium,/galena,/sygna,/counsel). A person has ONE identity: they sign in once, in Atrium, and every module resolves the same session. Modules keep their own schema and their own least-privilege roles — database isolation is unchanged — but identity is shared, not duplicated. What a module still owns alone is its domain settings (Galena's storage and encryption, Sygna's rates, Counsel's scoring). Because there is one origin there is no cross-origin handoff to design: no signed assertion, no audience binding, no SameSite dance. A design that invents a token handoff for this topology is over-engineering.Four
admin@example.comrows is a defect, not a design. Any text saying "no cross-app SSO", "separate logins", or that Atrium "links but never signs you in" is stale — correct it. That model was inferred by an assistant, never chosen.The section is kept rather than deleted because the wrong turn is the instructive part. Stage B's mechanism — one PostgreSQL cluster with a shared
coreschema, i.e. two applications inside one database — was rejected on good grounds and stays rejected. What went wrong is that the goal, one account, was thrown out with the mechanism. The goal was never the problem, and it is reached a different way: three tables —app_user,sessionandmodule_permission— in a neutraldreddschema owned by Atrium's migrator, reached throughsearch_pathrather than by qualifying anything in the code. (Two, when this was written; the third arrived with the administrator/moderator split, which needed somewhere only the hub could write, and becamemodule_permissionwhen it also had to say who may open a module at all.) Everything else stays exactly as isolated as it is today.
This section described a plan that did not happen, and the difference matters.
The original shape was three stages ending in one deployment: Stage A separate applications shaped
alike, Stage B one PostgreSQL cluster with a shared core schema and a shared session table
giving "real SSO with no new protocol", Stage C one shell embedding Galena inside Sygna.
What shipped instead (2026-09-12) is separate applications sharing a package. Each has its own
deployment and its own database; what they hold in common is dredd-core, imported and pinned.
Stage A's "users exist twice; that is accepted and temporary" is no longer temporary — it is the
architecture. — false, and the load-bearing error. "Users exist twice" was always the defect
Stage A said it was; what changed on 2026-09-12 was only that the mechanism for fixing it was
rejected. Sharing a package is not a reason to duplicate people.
Three consequences, none of them oversights:
No SSO by shared cookie. A cookie scoped to a parent domain reaches the sibling, but the— stale. The diagnosis is right and the conclusion does not follow: the answer is the shared auth store,sessionrow it names lives in the other application's database, so it resolves to nothing. Real SSO would need a shared auth database or an identity provider. Separate logins are the default now.dredd.session, and at one origin there is no parent-domain cookie to scope in the first place. Separate logins are a defect being removed, not a default.- No cross-application foreign keys or joins.
matter.document_node_idwas always a plain UUID with no FK — that decision survives intact and is now permanent rather than transitional. (The shared identity tables are reached by cross-schema FKs todredd.app_user. That is a different thing: one platform-owned table every module points at, not two applications' domain tables joined to each other.) - Server-to-server authentication has to change. See §3.5: this is the one place where code in this repository is now built on a false assumption. (And the platform plan's cutover stage deletes it again once identity is shared — the per-user Galena token exists only because it isn't.)
Stage C's work is not wasted, but it does less than it said. — half of it dissolved. At one origin
GALENA_FRAME_ANCESTORS and
SESSION_COOKIE_DOMAIN still make the embedded case file work — a user who has signed into Galena
in the same browser gets an authenticated frame, because the cookie is Galena's own, and scoping
it to the parent domain is what stops a cross-site iframe dropping it. What it is not is single
sign-on: the user signs in twice, once per application.SESSION_COOKIE_DOMAIN has nothing to do: Galena's cookie is this origin's cookie. Only
GALENA_FRAME_ANCESTORS still matters, and it still has to be set in the Galena repository
(frame-ancestors defaults to 'none' there, and the setting takes an origin list), so the embed
remains a deliberate opt-in rather than something one origin hands you for free. And it does
become single sign-on — not by the frame, by the shared session.
3.5 Server-to-server calls
Sygna→Galena calls pass through the acting user's token rather than using a service account, so
Galena's authz remains the single authority on document access and there is no privilege-escalation
seam to defend. Every outbound call goes through integrations/galena.py, is retried with backoff, and
records an integration_event row for idempotency and audit.
The principle stands. The implementation was broken by the architecture change, and is now
fixed (services/credentials.py, services/secrets.py, /me/galena-token).
Five call sites — routers/matters.py (twice), routers/documents.py, routers/billing.py and
integrations/galena.py's helpers — send extract_token(request), which is Sygna's own session
or app token. That resolved under the superseded Stage B, where both applications read one
core.session table. With separate databases, Galena hashes that token, looks it up in its session
table, and finds nothing. Every Sygna→Galena call would fail authentication on first contact.
Nothing had broken, only because Sygna has never run against a live Galena — the connector is
covered by stubbing integrations.base.request, which tests Sygna's half of the contract and
cannot notice that the credential is meaningless to the other half. That is the limit of a stub,
and it is why this was found by reading the architecture rather than by a failing test.
The fix keeps the principle. Each user mints a galena_pat_… token in Galena and stores it in
Sygna once; the five call sites send that. The rejected alternative was a service account: one
credential, no setup step, and Sygna's authorization rather than Galena's deciding who may read a
client's documents. For privileged material that is the wrong trade.
Superseded for the platform, 2026-09-24. With
IDENTITY_SCHEMAset, the two modules resolve the SAMEsessionrow, so the token the caller already holds is a credential Galena can resolve and the five call sites forward it —services/credentials.galena_tokenis the one place that decides which credential to use. The setup step, the stored secret and the re-entry after a restore all go away, and the principle survives untouched: the call still carries the acting user's credential and never a service account.The apparatus below is kept, not deleted, because it is still correct for the STANDALONE deployment — two independently deployed applications genuinely do have two identity stores. The
upstream_credentialtable is kept for a second reason: it holds ciphertext somebody entrusted to this system, and destroying that inside the migration that merges the accounts would be a second irreversible act riding on the first. It simply stops being read.
Storing it made Sygna hold its first genuine secret at rest — everything else about a person here
is a hash, because recognition is all that was ever needed. It is encrypted with AES-256-GCM under
a key derived from SECRET_KEY, which lives in the environment and not in the database; backups
already exclude .env, so an archive holds ciphertext and nothing that reads it. Restoring onto a
host with a different key means every user re-enters their token, and the console says exactly that
rather than reporting the credential as missing.
3.6 Sygna on dredd-core (done)
Sygna is its own application, not a module. The module-host design was superseded along with
Stage B: the family is four separate deployments that depend on one package. — corrected
2026-09-23: Sygna is a module of the platform, and still its own deployment. The sentence
collapsed two different senses of "module" and got one of them wrong. Still true: Sygna runs as its
own FastAPI process, its own container, its own database or schema, and nothing is installed into
it — Galena's in-process module host is not this, and Sygna is not a plugin of anything. No
longer true: "four separate deployments" as a product statement. The family is one platform at
one origin with four modules on four paths, sharing an identity store. Where this plan says
"module" about Sygna's internals, it still means its own routers/services packages.
Adoption is done (de18ef1, repinned b1a9d42): dredd-core is pinned by tag in
requirements.txt, and Base, the mixins, the seven identity/tree models, authz, AuthService,
security, audit, the engine factory, the error hierarchy and create_enum_types are imported
rather than copied. SHARED.md is no longer a manifest of files to keep diff-clean — it records what
core owns, what Sygna adds, and the three files still genuinely copied because none of them is
importable code.
The module plan's own sequence is P1 depend on the core package → P2 move to a sygna.* schema →
P3 ethical walls onto the authz overlay hook → P4 integrations into Connect → P5 console entry. Two
things about that order, found by reading it against what Sygna actually is:
-
P1 cannot start. It depends on core prerequisite #4,
coreas an installable package, and no Dredd core repository exists yet. Nothing in Sygna unblocks it; it is core work. -
P4's seam could start, and did. The plan moves
integrations/into Galena Connect as registered connectors; Connect has no registry to register with yet, so the registry is built here (integrations/registry.py) and the connectors describe themselves to it. It paid for itself immediately: the admin screen's inventory was a literal in the router, and it had been telling administrators that the KRS and Biała lista connectors were phase 2, not started for months after they went live. A derived list cannot drift that way. -
P3 could start, and did. The overlay hook is prerequisite #3, and Sygna is its only named consumer — so the seam is built here, in
services/authz_overlay.py, with the wall policy moved out toservices/walls.py. The resolver body is now Galena's line for line. When the hook moves intocore, this is a registration rather than a rewrite, and the work that proves the hook's shape is already done: a singlerole()callback is not enough. Four paths answer access questions — one node, a batch of 200, a notification's recipients, a tree badge — and a hook that covers only the first leaves three holes. That finding belongs in the core design. -
P2 was done, and then undone — deliberately. The tables were split into
core.*andsygna.*on the morning of 2026-09-12, because Stage B meant one database shared with Galena and the split was how the two applications' tables would have been told apart. By that evening Stage B was superseded (§3.4): separate applications, separate databases. With nothing to tell apart and nothing to merge, the split was paying a second provisioning path (a superuser-onlyCREATE SCHEMAmirrored in CI) and asearch_pathlistener on every connection,for a migration that is not coming. Everything is unqualified, in whatever schemasearch_pathnames —publicon a local stack,sygnain the family's shared managed database.Corrected 2026-09-23: a merge is coming, and the undoing still stands. What moves is exactly two tables,
app_userandsession, and they do not move into acore.*namespace inside this application's database — they move into a neutraldreddschema at the cluster level, owned by Atrium's migrator, reached by puttingdreddsecond in each role'ssearch_path. So nothing here becomes schema-qualified, which is precisely what the split would have cost and what removing it bought. The reasoning that killedcore.*was right; the conclusion drawn from it — that no merge would ever happen — was not.Worth keeping the reasoning rather than the code: the doing and the undoing were cheap for the same reason — nothing is deployed, so
0001_initialis still an edit rather than a data migration on a live database. That window is the only thing that made a wrong turn this cheap to reverse, and it closes the first time this runs anywhere. It has closed: this now runs on a live box, so the identity merge is a data migration and a rehearsal on apg_dumpcopy, not an edit. -
P3 could start, and did. The overlay hook is prerequisite #3, and Sygna is its only named consumer — so the seam is built here, in
services/authz_overlay.py, with the wall policy moved out toservices/walls.py. The resolver body is now Galena's line for line. When the hook moves intocore, this is a registration rather than a rewrite, and the work that proves the hook's shape is already done: a singlerole()callback is not enough. Four paths answer access questions — one node, a batch of 200, a notification's recipients, a tree badge — and a hook that covers only the first leaves three holes. That finding belongs in the core design.
The module plan's inventory of Sygna is also stale: it lists firm, matter, party, questionnaire, pleading, time_entry, ethical_wall. Sygna has 31 tables and no questionnaire — that is Counsel
Scorecard's. pleading is not a table either; documents are generated and streamed, never stored.
P2 is a 24-table move, not a 7-table one.
4. Domain model
Strict Galena layering applies: routers → services → models. Routers never build SQL; services own
domain logic. A bare db.get(Model, id) by primary key in a router is the only exception.
4.1 Tables
Parties and clients
party— a person or organisation.kind(person/organisation), names,pesel,nip,krs,regon, addresses,is_pep,risk_rating,edoreczenia_address. One table for clients, opposing parties, courts and experts — because the same entity plays different roles in different matters, and the conflict engine must see all of them in one place.party_link— related entities (parent company, beneficial owner, group member) with a typed relation. Feeds conflict checking beyond exact-name matching.party_alias— normalised name forms (declension stems, former names, transliterations).
Matters
matter— the aggregate root.node_id(its place in the tree),document_node_id(→ Galena project),reference(internal number),name,client_party_id,practice_area,status,responsible_lawyer_id,originating_lawyer_id,opened_at,closed_at,fee_type,value_in_dispute(wps), and the court block:court,department,case_signature(sygnatura),instance.matter_party— party + typed role (powód,pozwany,interwenient,pełnomocnik strony przeciwnej,biegły,świadek,sąd) +is_adverseflag. The adverse flag is what the conflict engine keys on.matter_note,matter_task.
Conflicts and access
conflict_check— a run record: who ran it, against what, the candidate hits, the outcome (clear/waived/declined), the waiver document, who decided. Never deleted. This is the firm's evidence if a conflict is ever alleged.ethical_wall—(matter_id, user_id, mode: allow|deny). Deny wins over any inherited grant.
Time and money
time_entry— matter, user, date,minutes(stored as integer minutes; UI works in 0.1 h), narrative, activity code (UTBMS optional),billable,rate,write_off_minutes,invoice_id.expense— disbursements:opłata sądowa,opłata skarbowa(17 zł), experts, translators, travel.rate_card+rate_card_entry✅ built — per-firm, per-client and per-matter hourly rates, effective-dated. Resolution (services/rates.resolve) walks matter override → matter card → client card → firm card → house setting, and within a card person → grade → fallback, returning the rate and where it came from. It resolves for the date of the work, not today.lawyer_profilecarries the grade, becauseapp_useris byte-identical with Galena's.invoice+invoice_line— with the KSeF block:ksef_number,ksef_status,ksef_sent_at,upo.client_deposit+deposit_movement— client money held on account, per-matter balance, check constraint: balance never negative.
Deadlines and the court calendar
deadline✅ built — matter,kind,due_date,source(statute/court/contract/internal),source_correspondence_id,owner_id,confirmed_by_id,confirmed_at,completed_at. The confirm-by-a-second-person flow is a column, not a convention. Escalating reminders are built (services/reminders.py): sparse milestones (14/7/3/1/0), one overdue notice, one escalation after three days to whoever manages the matter — falling back to the owner in a solo practice — and an idempotency key enforced by a database constraint, so the scheduler is safe to run at any frequency.notification+notification_pref✅ built — Galena's column shape (SHARED.md) plus adedupe_keyunique per recipient. Ethical walls filter recipients, so a notification can never reveal a matter the reader is walled off from.court_event✅ built — hearings: date/time, court, room, attending lawyer.
Correspondence and integrations
correspondence✅ built — one row per inbound/outbound item from e-Doręczenia, Portal Informacyjny or post.channel,direction,legal_service_date(the field that starts every clock),received_at,external_ref,matter_id,document_path(its location inside the Galena project). Built ahead of the connectors on purpose: the expensive part is not fetching a document, it is deciding what a service date means and making every derived deadline point back at it. Items land unassigned — nothing guesses which matter a letter belongs to. A service date is correctable until a deadline derives from it, then refused. Idempotency is a partial unique index on(channel, external_ref), so a connector that re-polls cannot duplicate an item.integration_event— outbound/inbound call log with an idempotency key. Every government API call lands here.
Intake / the CRM half
lead— enquiry, source, referrer, stage, estimated value, linkedconflict_check, and the conversion to amatter.pitch— tenders, panel appointments, RFPs.
Compliance
aml_case,aml_check— CDD records, beneficial-owner verification against CRBR, PEP/sanctions screening, risk assessment, 5-year retention. Structurally separated from matter content, since the AML duty applies only to defined transactional activity and privileged advisory work must not leak into it.professional_record— per-lawyer OC insurance policy,ORA/OIRPnumber, CPD points.
4.2 Authorization
services/authz.py stays the single authority, copied from Galena, with one addition:
effective_role(user, node) → Galena's ancestor-or-self resolver, unchanged
matter_role(user, matter) → effective_role(user, matter.node)
then: ethical_wall deny → None (404, hide existence)
ethical_wall allow → at least viewer
Deny-by-default for named individuals is what an information barrier actually requires; role-based
access alone cannot express it. Routers call assert_can_read / assert_role before every read and
write, exactly as in Galena.
Walls are administered from outside the barrier. matters.assert_wall_admin authorizes wall
management against the matter's parent container, not the matter itself. Authorizing it on the
matter would let anyone lock themselves out permanently — the deny that hides the matter also
removes their manager role on it, so there is no way back short of a DBA. Putting up a barrier is a
supervisory act, and it reads correctly as one. (Found during implementation, by the integration
test that walls an admin and then tries to lift the wall.)
4.3 Confidentiality architecture
Tajemnica adwokacka is a stronger regime than RODO and both apply at once. The constraints are
architectural, not policy documents:
- EU/PL hosting, contractually named data-centre location. Self-hosted Docker Compose is the default deployment, which makes this the operator's choice — a genuine advantage over SaaS rivals.
- Append-only
audit_logwith theapprole holding no UPDATE/DELETE — inherited from Galena and enforced in the migration. The audit log is a confidentiality control here, not a nice-to-have. - Encryption reuses Galena's self-describing blob format for anything Sygna stores at rest.
- No client data leaves the box by default. Any AI feature must be EU-hosted inference with contractual no-training terms, switchable off per matter, and off by default.
- Government API calls are the only outbound traffic, all funnelled through
integrations/and logged inintegration_event.
5. Integrations
All external I/O lives in backend/app/integrations/, behind a Connector protocol, called only from
services/. Never from a router. Each connector: typed config from Settings, httpx client with
timeouts and backoff, idempotency key, integration_event row, and a fake for tests.
| Connector | Priority | Notes |
|---|---|---|
edoreczenia.py |
P0 | UA API v3 only — v1/v2 were switched off 1 Jan 2026. Poll the mailbox, ingest EPO/EPD receipts, capture legal_service_date, resolve addresses via BAE, file the document into the matter's Galena project. Request test-environment access from gov.pl on day one — the queue, not the code, is the schedule risk. |
ksef.py |
P0 | KSeF 2.0. Receiving is mandatory for everyone since 1 Feb 2026; issuing since 1 Apr 2026. Issue invoices, handle offline24 fallback (submit by the next business day), store the KSeF number and UPO, manage certificates/tokens. |
registers.py |
P1 ✅ built (KRS + Biała lista) | Auto-fills a party from KRS — name, legal form, NIP, REGON, address, e-mail, and the e-Doręczenia (BAE) address, a genuine head start on Phase 2 — plus sposobReprezentacji. Biała lista adds VAT status and the registered bank accounts (verify before a disbursement leaves the client account). Correction to the original plan: the KRS API masks the names of natural persons (N**********), verified against three unrelated companies. Officers and shareholders therefore cannot be pulled into the conflict engine from this API — Sygna records their count and functions, flags the redaction, and asks for the names by hand. CEIDG, REGON/BIR1, VIES and CRBR remain to do; CEIDG and BIR1 need credentials. |
pisp.py |
P2 | Portal Informacyjny Sądów Powszechnych. Sync case events, hearings and served documents; capture the deemed-service date. No open public API — access mechanics must be established first (incumbents ship connectors, so it is possible). Filing via PI becomes obligatory for adwokaci/radcowie on 1 Mar 2027 — that date anchors the roadmap. |
saos.py |
P3 | Open case-law API. Free case-law lookup without a LEX/Legalis licence. |
galena.py |
P0 | Project creation, file write, tree read — see §3.5. |
Protocol details (SOAP vs REST, signature format, auth) for e-Doręczenia and KSeF must be verified against the current gov.pl specification before implementation; treat anything in this document about their wire format as directional.
6. Frontend
Same shell, new screens. Hash routes mirror Galena's #/n/<id> style.
| Route | Screen |
|---|---|
#/ |
Pulpit — my deadlines this week, unconfirmed service dates, unbilled time, open drafts |
#/matters · #/m/<id> |
Matter list · matter detail (parties, deadlines, time, documents, correspondence) |
#/clients · #/p/<id> |
Party list · party detail with related entities and matter history |
#/time |
Time sheet — a hand-rolled editable grid, following the _csvMount/_csvRender pattern |
#/calendar |
Deadlines + hearings. The one screen that may justify a committed Vite bundle |
#/billing |
Pro-forma review → invoice → KSeF status |
#/inbox |
e-Doręczenia and Portal Informacyjny items awaiting assignment to a matter |
#/intake |
Leads and pitches, with the conflict gate |
#/admin |
Users, access, integrations, AML settings, backup |
Conventions carried over: esc() every dynamic value; bearer token in memory only, cookie session
primary; one render funnel per screen so listeners do not accumulate; unsaved-changes guard on any
form; font-variant-numeric: tabular-nums everywhere money and time line up in columns.
PL-first i18n. Source strings stay English (that is how I18N.pl keys work), but the Polish
translation is part of the definition of done for every screen, and the legal vernacular in §7 is
authoritative for the PL side.
7. Terminology — Polish UI, English internals
Galena's first invariant is "de-jargoned UI, technical internals". Sygna's version: the UI speaks the vernacular of a Polish law firm; code, routes and tables stay English.
| UI (PL) | Code / route |
|---|---|
| Sprawa | matter |
| Sygnatura akt | case_signature |
| Klient / Strona | party (client_party_id, matter_party) |
| Strona przeciwna | matter_party.is_adverse |
| Konflikt interesów | conflict_check |
| Termin | deadline |
| Data doręczenia | legal_service_date |
| Rozprawa | court_event |
| Karta czasu pracy | time_entry |
| Wydatek / Opłata | expense |
| Faktura | invoice |
| Depozyt klienta | client_deposit |
| Akta sprawy | the linked Galena project |
| Kancelaria / Dział / Zespół | node (workspace / group / folder) |
8. Repository layout
sygna/
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
models/ identity (copied) · node (copied) · party · matter · conflict
· time · billing · deadline · correspondence · compliance
services/ auth · authz (copied + ethical walls) · nodes (copied)
· parties · matters · conflicts · deadlines · time · billing
· correspondence · aml · audit · notify · stats · search · settings
integrations/ base (Connector protocol) · galena · edoreczenia · ksef
· registers · pisp · saos
routers/ auth · users · admin · nodes · permissions · parties · matters
· conflicts · deadlines · time · billing · correspondence
· intake · dashboard · search · health
alembic/ 0001_initial (pgcrypto, enums, create_all, least-privilege grants)
scripts/license_gate.py
tests/ DB-free unit tests + integration gated on SYGNA_RUN_INTEGRATION=1
frontend/ index.html · app.css · app.js · sw.js (no build)
db/init/01-roles.sh
docs/CRMecenas-Discovery-Report.md
docker-compose.yml · .env.example · .github/workflows/ci.yml
PLAN.md · SHARED.md (Galena sync list) · CLAUDE.md · README.md · LICENSE (Apache-2.0)
9. Invariants (destined for CLAUDE.md)
- Polish vernacular UI, English internals. Keep the §7 mapping consistent across console and docs.
- Strict layering: routers → services → models. No
select(...)/db.add/db.executein a router. services/authz.pyis the only access authority. Ethical-wall deny wins over any inherited grant. No access → 404, never 403 (existence is itself privileged).- A matter is a leaf of the node tree, mirroring Galena's project rule. Its documents live in the linked Galena project, never in Sygna's database.
- Append-only audit. The
appDB role holds no UPDATE/DELETE onaudit_log.migratorowns DDL. conflict_checkrows are never deleted or edited. Supersede, don't mutate.legal_service_dateis set once, from the source system, and is never inferred. Every derived deadline points back to thecorrespondencerow it came from.- All external I/O goes through
integrations/, with anintegration_eventrow. Nohttpxcall anywhere else in the codebase. - Files shared with Galena stay diff-clean. Change both repos in one commit; record it in
SHARED.md. - Core stays permissive. Apache-2.0; CI denies GPL/AGPL/SSPL. Copyleft or heavyweight components are optional sidecars, never core — same policy as Galena.
- No build step for the console. The single exception is a committed Vite bundle with a working
fallback, following the
frontend/static/editor.jsprecedent. - Money in integer minor units, time in integer minutes. No floats anywhere near an invoice.
10. Roadmap
Phase 1 — the spine. ✅ Done (Aug 2026). Repo scaffold mirroring Galena (compose, a reverse proxy since retired for the
backend's own edge, roles, CI, licence gate). Copied identity/node/authz/errors layer. party (+aliases, links),
matter, matter_party, ethical_wall, conflict_check, lead, deadline, court_event,
time_entry — 18 tables, 70 routes. Console in Polish: pulpit, matters, matter detail
(parties / deadlines / time / access), parties, intake, timesheet, admin. Conflict check at
intake — blocking, with a permanent decision record. Galena case file created per matter and
deep-linked. Verified against a real PostgreSQL 16: migration + seed, 47 tests (32 DB-free +
15 integration), least-privilege grants, licence gate, console boots clean.
Not verified: the Galena connector against a live Galena instance — none was available.
Phase 2 — the Polish moat. The receiving end is already built: the #/inbox screen,
assignment to a matter, and deadlines derived from a service date all work today with manual entry.
What is left is the feed — e-Doręczenia (UA API v3 + BAE) writing through
services/correspondence.record, so the connector inherits the rules rather than re-implementing
them. Then KSeF 2.0 issuing and receiving. Then the registers connector for party auto-fill.
Start the e-Doręczenia test-environment request before writing any of this.
Phase 3 — money. ✅ complete. Disbursements with pass-through VAT handling, invoices with
a draft → approve → issue flow, credit notes, client-money deposits on a ledger that cannot go
negative, and the full management set: realisation (billing and collection, the latter net of
VAT), utilisation against real Polish working days, matter profitability against a cost
rate — reporting incomplete rather than a flattering zero when one is missing — lock-up
(WIP days + debtor days) and an aged-debt ageing table. Every report is filtered through the
authz resolver. KSeF columns exist; the connector is Phase 2.
Phase 4 — the wedge. Portal Informacyjny sync. Hardest integration, highest switching cost, and tied to the 1 Mar 2027 obligation.
Phase 5 — depth. Document generation with Polish declension, PAdES signing via a QTSP, the AML/KYC
module, and a client portal. (The Galena convergence is done and turned out smaller than this
line implied: it was adopting a package, not merging two deployments — §3.4.) (The court-fee and koszty zastępstwa calculators were pulled forward and are built — services/fees.py, pure computation with
the schedules as auditable data. The figures still need checking against the current statutes.)
11. Open questions and risks
Blocking, needs an external answer
- e-Doręczenia test-environment access — lead time unknown, gates Phase 2.
- Portal Informacyjny integration for third-party vendors — the access mechanism and its legal basis must be established before Phase 4 can be scheduled.
Decided (2026-08-13)
- Deployment: self-hosted, as Galena. Docker Compose (the backend is its own edge), no managed dependency. A hosted
offering may follow but never replaces the self-hosted path — it is what makes
tajemnica adwokackadefensible. - Shared code: a separately-versioned package.
vendor + enforce, then merge— this call was reversed, and the reasoning behind it dissolved rather than being refuted. The argument against a package was that versioning a library apart from the schema it describes buys a distributed-versioning problem "for two apps that deploy together". They do not deploy together any more: separate applications, separate databases, separate release cadences. Once that was true, vendoring bought the drift problem instead — whichshared_check.pycould detect and never fix.dredd-coreis pinned by tag, so the distributed-versioning problem is real but bounded: a core change is a tag bump and a deliberate repin in each application, and the alternative was two copies silently diverging. - In-house departments: configurable.
practice_modesetting, not a second product. - Mobile breakpoint: 880px, matching Galena.
- Commercial company-data provider: yes. Wanted for unmasked officers and beneficial owners.
Build it behind the
integrations/boundary, off by default, with the confidentiality controls below — a conflict search discloses that the firm is considering acting for or against a named party, so every query is a disclosure and needs a DPA, a sub-processor entry, local caching so a name is sent once, and an audit row per outbound lookup.
Technical risks
-
The no-build console versus the calendar screen.Resolved, and the worry was misplaced. The month view shipped as seven columns of CSS grid over a JSON payload — no library, no bundle, no committed build artefact, and the mobile version is the same markup with the grid collapsed to one column. The committed-bundle precedent remains available for a future screen that genuinely needs it; a calendar did not. -
Polish full-text search. PostgreSQL ships no Polish configuration. Preferred route is Morfologik (BSD) for stemming; the Hunspell Polish dictionary is tri-licensed GPL/LGPL/MPL, so take the MPL-2.0 branch to stay inside the licence gate. Validate this before relying on it.
Shipped in the meantime:
services/search.pydoes substring matching with the diacritic fold expressed in SQL (translate(lower(col), 'ąćęłńóśźż', 'acelnoszz')) — no extension, no denormalised column, andlodzfinds Łódź. What it does not do is stem:zażaleniadoes not matchzażalenie, and a search forsprawawill not findsprawie. That is the gap Morfologik closes, and it is a search-quality gap, not a correctness one — the conflict engine has its own stemmer (parties._stem) and does not go through this path. Each kind scans at most 200 candidate rows and reports when it hit the cap; a firm large enough for that to bite is a firm large enough to want the real index. -
Declension in generated documents.
services/declension.pyimplements the regular patterns of Polish surname and given-name declension and reportscertain=Falsefor anything else — foreign names, bare trading names, unusual stems. It is deliberately not a morphological analyser: Morfologik (BSD) is the same documented upgrade named for search above, and nothing outside that module depends on how it works. The risk it carries is bounded by design — an unrecognised name reaches the document as a nominative with a warning attached, never as a confidently wrong form. -
Name clearance. "Sygna" has had no trademark or domain check.
-
Government API instability. KSeF and e-Doręczenia specs have both moved repeatedly. The
integrations/boundary plusintegration_eventreplay is the insurance; version every connector.