- Correspondence: the inbox's undated list held items already filed in a matter and showed and counted them for everyone. It is now filtered to the reader (correspondence.undated_for), including the dashboard card. assign is authorized on the matter an item leaves as well as the one it enters, and an item with derived deadlines no longer moves. The undated reminder goes only to recipients who may read the item's matter. - Conflict hits: the search still looks across every wall, but a hit in a matter the reader cannot open no longer names it (conflicts.visible_hits, matter_hidden). conflict_out requires the reader's hits. - AML: deleting a matter cascaded to its assessments, and the runtime role's missing DELETE did not stop it (a cascade runs as the table's owner). nodes.delete refuses in words; revision 0007 drops the cascade. - Opening a matter: the conflict check must cover the client (the engine's name match against name and aliases) and the lead named on the request. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
63 KiB
CLAUDE.md
Guidance for Claude Code when working in this repository.
What this is
Sygna — practice management (CRM + matters + time) for Polish law firms. It is a module
of the Dredd platform, served under the path /sygna alongside Atrium, Galena and Counsel.
Stack: FastAPI + SQLAlchemy 2 + Alembic + PostgreSQL 16 / 17, Argon2id auth + server-side
cookie sessions, a no-build static console (vanilla JS), Docker Compose (no reverse proxy — the backend is its own edge). License
Apache-2.0; every dependency is permissive (no copyleft).
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.com rows 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; PLAN.md §3.4 recorded it as the architecture, and
it is not.
How far that has got. Both halves have landed. The one-address mount (ROOT_PATH=/sygna, a
document.baseURI-derived API base), and the shared identity: with IDENTITY_SCHEMA=dredd set,
app_user, session and module_permission live in a neutral schema owned by Atrium's migrator,
Sygna READS them and never writes them, and the cookie a person was given when they signed in at
the hub is the cookie this module resolves. Revision 0003_shared_identity is the cutover;
0004_module_permission is the rename that reaches the databases 0001 built under the old core.
IDENTITY_SCHEMA empty is the standalone application, which owns its own accounts and still has
to work — same code, one predicate (settings.shares_identity). What never changes is the data
isolation: Sygna keeps its own database on a local stack and its own schema sygna in the
family's shared managed database, and what it shares with the other modules in code is
dredd-core, imported, not copied.
Sygna owns matters, people, time and money. Galena owns documents and their history. Neither
duplicates the other: a matter's case file (akta sprawy) is a Galena project, referenced by
matter.document_node_id.
Read PLAN.md before any substantial change — it holds the compatibility contract
with Galena, the roadmap, and why things are the way they are.
SHARED.md records what dredd-core owns, what Sygna adds on top, and the three
files still genuinely copied from Galena because none of them is importable code.
Where things live
backend/app/
main.py config.py db.py deps.py errors.py security.py enums.py schemas.py seed.py
restore.py (the one-shot `python -m app.restore`) observability.py logging_config.py
models/ AppUser · Session · AppSetting · AuditLog · Node · PermissionGrant · Favorite
all come from `dredd_core` — imported, not copied (SHARED.md)
party (+alias, link) · matter (+matter_party, ethical_wall)
conflict (conflict_check, lead) · correspondence · deadline (+court_event)
timelog · notification (+prefs)
billing (expense, invoice, invoice_line, client_deposit, deposit_movement)
rate (rate_card, rate_card_entry, lawyer_profile)
aml (aml_assessment) · template (document_template)
services/ auth (core's AuthService + Sygna's policy) · authz (core's, + the walled badge)
credentials (each user's Galena token) · secrets (AES-GCM, key from the env)
walls (the wall policy, registered on core's overlay hook)
nodes (the node-kind registry) · audit (re-export) · settings
parties (name normalisation) · conflicts (the engine) · matters
correspondence (the inbox + service dates) · deadlines · timelog · leads · stats
billing (disbursements, invoices, client money) · reports (realisation,
utilisation, profitability, lock-up, aged debt) · workdays (PL holidays, pure)
fees (pure: opłaty sądowe + koszty zastępstwa) · rates (resolution)
declension (pure: Polish name declension) · documents (pisma + faktury)
amount_words (pure: kwota słownie) · templates (the firm's own .docx)
calendar (month view: deadlines, hearings, art. 115 k.c.)
aml (risk scoring + the due-diligence record)
registers (pure mapping of KRS / Biała lista payloads)
notify (idempotent push) · reminders (the engine + lifespan scheduler)
backup (whole-instance archive + atomic restore, own scheduler)
search (one box over every record type, permission-filtered)
integrations/ base (retries, UpstreamError) · registry (the self-describing inventory)
galena · registers (KRS, Biała lista)
email (SMTP, stdlib only — the one non-HTTP connector)
[e-Doręczenia/KSeF: Phase 2]
routers/ health auth users admin nodes permissions parties conflicts intake
matters deadlines correspondence timelog billing reports fees rates
registers search documents templates calendar aml
notifications dashboard
tests/fixtures/krs_odpis_aktualny.json trimmed real KRS response — the mapper's test input
alembic/ env + 0001_initial (pgcrypto, enums, create_all, least-privilege grants)
+ 0002_runtime_grants (dredd-core's loud, schema-aware grants for DB_APP_ROLE)
+ 0003_shared_identity (THE CUTOVER: merge this schema's accounts into the
platform's by lower(email), drop the local identity tables; a no-op standalone)
+ 0004_module_permission (renames the local `module_moderator` `0001` built under
dredd-core v0.10.x; a no-op on the platform, where the table is the hub's)
frontend/ index.html · app.css · app.js (no build step, PL-first)
Tabler icons vendored into app.js's ICN map (CREDITS.md)
db/init/ 01-roles.sh (creates the app + migrator roles)
db/managed/ provision.sql (dredd-core's rendering, CI-checked) · README.md (Sygna's runbook
in the family's shared managed database, plus the database-wide checklist)
docker-compose.yml · docker-compose.managed-db.yml · .env.example · .github/workflows/ci.yml
docs/CRMecenas-Discovery-Report.md (research; §4 superseded by PLAN.md)
Commands
DREDD_CORE_TOKEN=… docker compose up -d --build # full stack; the token is a build secret (private dep)
cd backend && pytest # DB-free unit tests; integration auto-skips
SYGNA_RUN_INTEGRATION=1 pytest # full API loop (needs a migrated+seeded Postgres)
python scripts/license_gate.py # CI license gate locally
python scripts/deploy_check.py # compose/Dockerfile/edge/.env coherence
python scripts/deploy_check.py --env ../.env # + the managed-database URLs (TLS, pooler, roles)
python -m app.restore [NAME --yes] # list backups / restore one, one-shot (needs the migrator URL)
python -m dredd_core.managed check --url DATABASE_URL --expect-schema sygna --require-tls \
--app-role sygna_app --migrator-role sygna_migrator \
--append-only audit_log --no-delete conflict_check aml_assessment # managed-database preflight
python scripts/shared_check.py # byte-identity with ../Galena (SHARED.md)
BOOTSTRAP_ADMIN_PASSWORD=… python scripts/walkthrough.py # drive the whole product, live
Invariants — preserve these
-
Polish vernacular UI, English internals. The UI says Sprawa / Klient / Termin / Karta czasu pracy / Konflikt interesów; code, routes and tables stay English. The mapping is in PLAN.md §7 — keep it consistent across console and docs.
-
Strict layering: routers → services → models. Routers never build SQL — no
select(...)/db.add/db.executein a router. A lonedb.get(Model, id)by primary key is acceptable. Services own every domain rule. -
services/authz.pyis the only access authority. Routers callassert_can_read/assert_rolebefore every read and write, and neverdredd_core.authzdirectly — core's resolver knows nothing about ethical walls, so a caller that imports it walks around every one of them. No access → 404, never 403 — the existence of a matter is itself privileged. -
authz.pyholds no Sygna policy and defines exactly one function. Role resolution isdredd_core.authz's — grants, ownership, the ancestor chain — and core applies registered overlays on every path that answers an access question: the single node, the batch a list screen uses, and a notification's recipients. The one thing Sygna adds isaccess_statereturningwalled, a label rather than a decision (core would saylocked, which is true and unhelpful).test_authz.pyasserts nothing else is defined there. Never forkdredd_core.authzto add a rule — register an overlay. -
Ethical walls beat everything, and only ever deny. A row in
ethical_wallremoves every role on that matter, including owner, manager and instance admin. There is no mode: theallowmode this once had admitted somebody the grant tree gave nothing, which is a permission grant wearing a barrier's clothes — and exactly the escalation path core's restrict-only overlay hook exists to close. Anyone who needs access gets a grant. Walls are administered from outside the barrier:matters.assert_wall_adminauthorizes against the matter's parent container, because authorizing it on the matter itself lets anyone lock themselves out permanently. And since the parent decides who administers the wall, a move is authorized on the container it LEAVES as well as the one it enters, and only a moderator may move anything to the top level, where only workspaces may be (services/nodes.move, the one function that changesparent_id;test_node_move.pyfails on any other writer). Without the first, a matter's opener carried it into "Moje sprawy", became its wall administrator and lifted the partner's wall (QA 2026-10-07). The whole policy lives inservices/walls.pyand registers on core's hook (dredd_core.authz.register_overlay, v0.7.0) fromservices/__init__.py, so importing anything underapp.servicesinstalls it — a wall that only applies when some other module remembered to load it is not a wall.test_authz.pyguards the registration, because nothing else would fail if it were lost, and guards that the policy only ever denies rather than leaning on core to discard a promotion. -
Identity is the platform's; this module reads it. With
IDENTITY_SCHEMAset,sygna_appholds a column-restrictedSELECTonapp_user(neverpassword_hash,failed_login_countorlocked_until),SELECTplus a three-columnUPDATEonsession(last_seen_at,expires_at,revoked_at) andSELECTonmodule_permission— and no INSERT or UPDATE there at all, because a module that could write its own permission rows could admit anyone, promote anyone, and promote itself. So creating an account, resetting a password, admitting somebody to this module and minting an app token are not screens this module chose to hide: they are statements PostgreSQL refuses. TheAuthPolicyflags inservices/auth.py(identity_writes_enabled,local_login_enabled,app_tokens_enabled) are the matching sentence at the edge, so a refusal reads as a 409 with a Polish sentence rather thanpermission denied for table app_usersurfacing as a 500 — an error that names neither the column nor the privilege. Never widen a grant to make a screen work; move the screen to the hub. A role that can INSERT asessionrow can mint a working credential for the administrator. -
Single sign-on is one cookie and one
sessionrow, and that is the whole design. One origin, one module per path,SESSION_COOKIE_NAMEthe same in every app. No signed assertion, no audience binding, no redirect dance, noDomain=attribute. A design that invents a token handoff for this topology is over-engineering and must be rejected.Path=/is the one cookie attribute that matters — scope it to/sygnaand the other modules never see it.deps.LEGACY_SESSION_COOKIESkeeps reading the old name for one request so renaming it does not sign out the person performing the rename. -
app_usernever resolves locally. Addressing is thesearch_path(sygna, dredd, extensions) and Sygna's own schema must stay FIRST, oralembic_version, the enum types and every new table land in a schema its migrator does not own. The entire cost of that correct choice is one failure mode with no other symptom: an unqualifiedapp_userresolves tosygna.app_userif one exists, and everything keeps working — silently back to two rows per human and two passwords, which is the defect this change exists to end.main._assert_shared_ identityrunsdredd_core.identity_schema.assert_identity_schemaon every boot and refuses to start;0001builds the shared tables only when this install owns them (own_tables), and itsdrop_allis filtered for the same reason in the direction that destroys data. Never make the boot assertion conditional and neverDROP TABLE ... CASCADEin0003: that drop is the completeness proof for the foreign-key repoint. -
Three words, used exactly: ADMINISTRATOR is platform-wide, MODERATOR administers one module, USER may open it — and no row at all is no access. All of them are granted in Atrium; Sygna reads
module_permission(services/moderation.py) and writes nothing. The absence of a row is the point: before it, anybody the platform had heard of could open/sygnaand merely find it empty, and "you can see nothing" is not an access decision.moderation.assert_may_useis that decision, and it lives indeps.get_current_userbeside the token-scope check — one call covering every authenticated route, which is why no new route can forget it. Never move it to individual routers and never add an exempt route.deps.require_moderatoris still the ONLY administration guard here and this module defines no administrator-only guard at all — every power left in Sygna is module-scoped, and a route behind the wider tier is a route a moderator cannot reach while doing the job they were given. No router readsis_adminoff an account (tests/test_shared_identity.pychecks);services/auth.pyowns the one place it is written, and only standalone. Standalone all of it is inert: core answers"user"for everybody and resolves the moderator tier fromuser.is_admin, emitting no SQL — so both guards read the same in both deployments and a standalone Sygna never starts refusing its own users. -
A moderator does not walk through an ethical wall, and the ORDER is why. Core elevates a moderator inside
_base_role— exactly whereis_adminalready sits — andservices/walls.pyhangs on core's restrict-only overlay hook, which core applies afterwards, on every path that answers an access question. So the barrier takes back the role core just granted, for a moderator as for an administrator.services/__init__.pybinds both, on package import, for the same reason walls have always been registered there. Never "fix" a moderator's missing access by making the overlay grant: a seam that can widen access is a privilege-escalation path one bad overlay away, and core discards a higher return rather than trusting it. Auserrow reaches none of this: the only tierdredd_core.authzconsults is MODERATOR, sorole = 'user'answers one question — may this person open Sygna — at the edge and nowhere else. A permission row opens the front door; what is behind it is still the grant tree with the walls over it. -
Node kinds are a registry, not a database enum. Core stores
node.kindas text and leaves the vocabulary to each application:nodes.node_kinds()is core's containers plus what Sygna provides (matter). Contributing a kind costs nothing in core — no enum, no migration, nothing for Galena to agree to.NodeKindsurvives inenums.pyas a constants holder, and since aStrEnumcompares equal to its own string the comparisons all still work — but reads do not take.value, becausenode.kindis a plainstr. That is what broke on adoption. -
A matter is a leaf of the node tree, mirroring Galena's project rule.
nodes.LEAF_KINDSis the one definition. Sygna never creates a node of kindproject— those belong to Galena. Matter nodes are created only byservices/matters.open_matter, never by the nodes router: a matter node without itsmatterrow is an orphan the authz resolver cannot wall. -
The conflict check is a blocking gate, not a report.
open_matterrefuses a check that ispendingordeclined, and refuses one already used to open a matter (one check, one matter). Awaived/declineddecision requires a written reason. And the check must be a check on that client (matters.assert_check_covers): the engine's own name match against the client's name and aliases, and the lead named on the request must be the check's lead — otherwise a clear check on any unknown name opened a matter for anyone. -
A conflict hit never describes a matter the reader cannot open. The search looks across every wall (it has to), but on the way out
conflicts.visible_hitsblanks the matter fields of a hit in an unreadable matter and setsmatter_hidden; the hit itself — kind, severity, party, role — stays.conflict_outtakes the reader'shitsas a required argument, so a caller that forgets fails rather than leaks. The frozenconflict_check.hitsis never rewritten. -
A check's decision note must match its own
hit_count. An auto-cleared check with non-blocking hits says how many it found and why none required a human — never "brak trafień" next to a hit count of three. The row is read years later by somebody reconstructing why a matter was taken, and a note that contradicts the record makes the whole register untrustworthy. -
conflict_checkrows are evidence. Never edited after a decision (conflicts.deciderefuses a second one) and never deleted — theappDB role has no DELETE on that table. To change an outcome, run a new check. -
Sygna never files a GIIF report, and must not grow one. Art. 2 ust. 2 of the AML Act 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 transmitting privileged material to a state authority would be actively dangerous, and an automated one worse.
services/aml.pyrecords that a human decided, what they decided and when; the privilege analysis stays with the lawyer. -
An AML assessment is evidence, like a conflict check. Never edited after approval — a change of circumstances produces a new assessment that supersedes it — and the
approle has no DELETE onaml_assessment, enforced in the migration. Approval is refused without a description of the measures actually applied, without a reason when a matter is marked outside art. 2 ust. 1 pkt 14, and at high risk without either a beneficial owner or a written explanation of why one could not be established (art. 36). PEP forces high risk regardless of mitigating factors (art. 46): it is not a heavy scoring factor, it is an override, and a PEP who is also a long-standing client of a listed company must not average out to medium.retain_untilis stored, not computed — art. 49's five years is the clock that was written down at the time, not one recomputed under today's rule. A missing DELETE grant does not stop a cascade — PostgreSQL runs a referential action as the table's owner — soaml_assessment.matter_idcarries no ON DELETE rule (revision0007, likeinvoice.matter_id) andnodes.deleterefuses a subtree holding any assessment, in words, before the database does. -
Append-only audit. The
approle holds no UPDATE/DELETE onaudit_log(enforced in the migration).migratorowns DDL;appis DML-only. In a law firm the audit log is a confidentiality control, not an ops convenience. -
Managed Postgres = the family's shared managed database (db/managed/README.md): one database at a managed PostgreSQL provider for Atrium, Galena, Sygna and Counsel Scorecard, one schema each. Never name a provider — write "a managed PostgreSQL provider" / "managed Postgres" and keep provider know-how generic ("some poolers want
<role>.<tenant>user names", "download the provider's root CA from its dashboard", "keep the schema out of any auto-generated API", "a restore may drop custom role passwords"). Preserve:- Sygna's schema is
sygna, neverpublic, owned bysygna_migrator. Nothing in the code names a schema — the roles'search_path(sygna, extensions, set by dredd-core's provisioning) puts tables, enum types andalembic_versionthere, andcreate_all's existence check never sees another app's same-namedaudit_logorapp_user. Keep it that way: never schema-qualify, never hard-codepublic. - Role names are configuration, per application. Locally and in CI the roles are
app/migrator; in the shared databasesygna_app/sygna_migrator, because role names are cluster-wide and a sharedappwould let another app's migration grant back the DELETE that protectsconflict_check. The runtime role's name isDB_APP_ROLE(config.py); the grant migrations read it and nothing else needs a role name. A new revision that creates a table ends withruntime_grants_sql(...)again, with the sameappend_only/no_deleteas0002— that one call is all the grant code it needs. - Never migrate as
postgres(or any superuser / the platform admin), and0001's FIRST statement is what says so: dredd-core'smigration_preflight_sqlrefuses it by name (migration preflight: refusing to migrate as …) before anything is created — keep it first.0002's runtime grants repeat the same two checks, but they are reached only if0001succeeded, and aspostgres_managed0001did not: it died onrelation "app_user" does not exist, because that role's search_path never carriesdredd, so the first foreign key to the platform's accounts had nothing to bind to. Still refused, still nothing left behind (Alembic's one transaction) — but by accident, and naming neither the problem nor the fix. Grants fail loudly — a missing role, a grant that did not take or an evidence table still writable raises, never warns. Provisioning is dredd-core's (python -m dredd_core.managed provision), never hand-written SQL;provision.sqlis its rendering and CI fails when it is stale. - TLS only through
make_engine. Every engine — runtime, Alembic, the seed, restore — isdredd_core.db.make_engine, nevercreate_engine(a test greps for it): only it turns?sslmode=verify-full&sslrootcert=…into a verifying context for pg8000, and it refusesprefer/allow/disable.alembic/env.pyuses the URL directly, neverconfig.set_main_option(configparser breaks a URL-encoded%). - The family's one TLS rule (
dredd_core.db.require_verified_tls, applied bySettingsto both URLs, unconditionally): a database host counts as local when it is"",localhost,127.0.0.1,::1,postgresor listed inDB_LOCAL_HOSTS(comma-separated, optional); every other host must saysslmode=verify-full(withsslrootcertor the system store) or Sygna refuses to start —make_enginealone would still takerequire,verify-caand nosslmode(unverified TLS with a plaintext fallback). No provider host lists, no compose literal, no other opt-out (DB_REQUIRE_VERIFY_FULLis gone;deploy_check.pyfails if it returns). And never giveDB_APP_ROLEanenvironment:entry indocker-compose.managed-db.yml(a shell export would beat the.envthatdeploy_check.pychecked). - The provisioning's final revoke is not a wall. The platform admin (
postgres) keeps ADMIN OPTION on the roles it created and can make itselfsygna_migratoragain, so SQL-editor access at the provider is full control of Sygna's data. Never document it as protection against dashboard users. - Connections: through a pooler, its session mode, never transaction mode (port 6543 on
some providers); users
<role>.<tenant>where the pooler wants the tenant in the user name. The pool isDB_POOL_SIZE+DB_MAX_OVERFLOWper process, sized to the connection limit four apps share; one-shot processes (seed, restore, migrations) useNullPool.deploy_check.py --envchecks the URLs. - PostgreSQL 16 and 17: the local stack runs 16, managed providers commonly 17; CI runs the
suite on both plus a
managed-dbjob on 17 that provisions, migrates and tests exactly as the runbook says.db/managed/provision.sqlis rendered bypython -m dredd_core.managed provision --sql-only— re-render it, never hand-edit (CI fails when it is stale).
- Sygna's schema is
-
legal_service_dateis set once, from the source system, never inferred. It lives oncorrespondenceand is the only thing a procedural deadline may count from —received_atis the separate, operational fact of when the row appeared here, and nothing counts from it. Correcting a service date is refused once a deadline derives from it (moving one date that six deadlines were computed from is how a firm misses all six); delete those deadlines first, on purpose. Every derived deadline records how its date was reached in words (deadline.basis) and points back at the row viasource_correspondence_id,ondelete=RESTRICT— a deadline that has lost the document proving where its date came from is worse than a blocked delete. -
Correspondence is assigned to a matter by a human. Items land unassigned in the inbox; nothing guesses, because a plausible guess files a court letter in the wrong client's records. Moving a filed item is authorized on the matter it leaves as well as the one it enters (
correspondence.assign, the same rule asunassign), and an item deadlines were derived from does not move. The inbox's undated list also holds FILED items, so it is filtered to the reader and counted after the filter (correspondence.undated_for); only unassigned post is everyone's. -
Connectors write through
services/correspondence.record. Phase 2's e-Doręczenia and Portal Informacyjny connectors use the same function the console does, so they inherit the service-date and idempotency rules instead of re-implementing them. Idempotency is(channel, external_ref)— a partial unique index, so a re-poll cannot duplicate an item even under a race, and hand-entered items with no upstream id are unconstrained. -
Dual control on deadlines.
deadlines.confirmrefuses the creator forstatuteandcourtsources. A four-eyes check performed by one pair of eyes is theatre. -
A placeholder in a Word file is not in one piece.
{klient_dop}typed in Word can end up as three runs — a spell-check pass or a stray format change splits it — sotemplates.pyjoins a paragraph's runs, substitutes on the whole string and writes the result back into the first run. A per-run replace works perfectly on a file the developer typed and misses most placeholders in a real firm's letterhead. Headers and footers are filled too: that is where letterhead lives, and a template system that skips them is one nobody uses. An unknown placeholder is left visible, never blanked — a silent hole in a document is worse than a visible one. -
Uploaded templates are constrained, not trusted.
.docxonly, size-capped, macro parts refused whatever the extension claims, and stored under a name derived from the row id so the uploaded filename can never be a path. They live inDATA_DIR/templates/, which the backup archive already takes. A template is switched off, never deleted — a document generated last year was generated from something. -
A generated document can be filed into the Galena case file, through Galena's own API and with the acting user's token, so Galena decides who may write to a project. Filing is best-effort and reported: the document was produced either way, and the user has to know it is not in the file rather than assume it is.
integrations.base.requestgaineddata/filesfor multipart — the boundary keeps its one job — and the body is passed as bytes, because a retry has to send it again and an exhausted stream sends nothing. -
Sygna→Galena calls carry the ACTING USER's credential, never a service account. The principle is PLAN.md §3.5 and it has never changed: Galena's authz stays the single authority on who may read a case file, so there is no privilege-escalation seam between the two applications to defend. A service account would be one credential and no setup step, and would move the decision about who may read a client's documents out of Galena and into Sygna. Which credential is the one thing that depends on the deployment, and
services/credentials.galena_tokenis the only place that decides. On the platform both modules resolve the samesessionrow, so the caller's own token is forwarded (deps.extract_token) — nothing to mint, store, encrypt or re-enter, and one credential to revoke instead of two. Standalone the two apps have two identity stores, so it is thegalena_pat_…the user minted in Galena and stored once (Konto → Połączenie z Galeną). Note what shared identity does NOT remove: Galena is a separate deployment behind the same proxy, so the call still presents somebody's credential over HTTP. -
The Galena token is the only thing Sygna stores recoverably (and only standalone — on the platform nothing is stored at all). Everything else a person entrusts to this system is a hash — passwords Argon2id, session tokens sha256 — because Sygna only ever needs to recognise those. A Galena token has to be replayed, so it is encrypted (AES-256-GCM,
services/secrets.py) with a key derived fromSECRET_KEYin the environment, never in the database. The backup archive already excludes.env, so a stolen archive holds ciphertext and nothing that reads it. The corollary is deliberate: restoring onto a host with a differentSECRET_KEYleaves stored tokens unreadable and each user re-enters theirs — which is whycredentials.statusreportsunreadableas its own state, distinct from "none". No endpoint ever returns the token; the console shows a fragment. -
/healthzanswers two different questions. Plain is liveness — is the process up — and must never touch the database, because a blip that gets a healthy container killed is a worse outage than the blip.?deep=1is readiness:SELECT 1, 503 on failure, and it is what a load balancer must poll. The plain form used to answer both, returning 200 with the database unreachable, so a dead instance kept its share of the traffic. The deep form is unauthenticated, so it reports that it failed and never why — a hostname or a port in that response is reconnaissance. Compose's backend healthcheck uses the deep form. -
All external I/O goes through
app/integrations/, viaintegrations.base.request, and raises onlyUpstreamError. Nohttpxcall anywhere else in the codebase. A connector failure must never break the primary action — seegalena.try_create_case_file. -
The integrations screen is derived, never written out. Each connector describes itself in
integrations/registry.pyterms next to its own code, and registers on package import. The literal it replaced had drifted: it announced KRS and the Biała lista as phase 2, not started long after both had been run against the live government services, and never mentioned SMTP at all.ready/off/plannedare three different answers and must render as three different things — "not built yet" is a roadmap fact, "switched off" is this firm's decision. Describing a connector never calls anyone;probe()does, and only when an administrator presses the button. A probe reports a failure, it does not raise, and an unconfigured connector says that rather than reporting a connection error against an empty address. -
Money in integer minor units (grosze), time in integer minutes. No float near an invoice.
TimeEntry.amount_minoris the single definition of how time becomes money; time rounds up to 6-minute units, and the amount rounds down, in the client's favour. The console converts złote↔grosze at the input box (zlToMinor/minorToZl) and nowhere else. -
The invoice document is summed from the invoice's own lines, never recomputed.
documents._vat_summaryadds upInvoiceLine.vat_minor; it does not re-derive VAT from the net.services/billing.pyalready decided that VAT is taxed per line and never on the total, and a second calculation in the renderer could disagree with the invoice it is printing.REQUIRED_ELEMENTSholds art. 106e ust. 1's list with the provision on each, and a test asserts they reach the page — the statute is checked against the output, not against memory. A missing seller NIP or address is a warning, never a blank space: an invoice without them is not a valid invoice, and printing an empty gap would hide that. -
An issued invoice is immutable.
issuedis the point of no return: the correction is a credit note (faktura korygująca), never an edit. A credit note mirrors every line with the sign flipped and releases the underlying time and expenses back to unbilled, so a mistake is re-billed properly rather than silently written off. One credit note per invoice. -
An invoice number is assigned at issue, never at draft — a gap in the sequence is a question from the tax office. Derived from the highest existing number, so a restored backup cannot hand the same one out twice.
-
Approval is a separate act from issuing.
approved_by_idrecords who read the narratives the client is about to read; that review is why firms bill late and correctly. -
VAT is summed per line, never taxed on the total — three lines of 3,33 give 2,31, not 2,30. Pass-through disbursements (opłata sądowa, skarbowa) go on at 0%: recharged at cost, they are not our supply. The VAT treatment of disbursements needs an accountant's sign-off — the same caveat as the fee schedules.
-
Client money can never go negative.
client_deposit.balance_minorcarries a CHECK constraint, so a bug inservices/billing.pycannot overdraw a client's funds. -
Money is an approver's business. Recording time is
editor; deciding what a client is asked to pay isapprover(billing.assert_can_bill). -
Every report states its basis, and is filtered to what the reader may see. Standard is before write-offs; billed means it reached an issued invoice (a draft is not billed, a cancelled one released its work); collection is net of VAT, because VAT is not revenue.
reports.visible_mattersruns the same authz resolver as everything else — a management report that quietly includes a walled matter is a leak wearing a spreadsheet. -
The calendar explains art. 115 k.c.; it never applies it. A deadline falling on a Saturday, Sunday or public holiday is drawn on the day it is recorded for, with
moves_toand a note saying when it actually expires.due_dateis never silently shifted: that date was derived from a service date and confirmed by a second person, and rewriting it would break the provenance chain the deadline exists to preserve. The calendar explains; it does not edit. -
Utilisation counts real Polish working days (
services/workdays.py, pure and tested, Easter via the anonymous Gregorian algorithm). Treating Christmas as available flatters everyone by a few per cent.next_working_dayis there for art. 115 k.c. when Phase 2 has a real service date to count from. -
Profitability without a cost rate reports
incomplete, never a flattering zero.lawyer_profile.cost_rate_minoris the input; a matter with any uncosted time is flagged in the API and badged in the console. -
A generated document never guesses silently.
services/declension.pyreturns every form with acertainflag, anddocuments.renderturns every uncertain one into a warning the console shows above the download button.services/parties.pymay over-match because a conflict screen should show too much; a pleading is the opposite case, so declension errs towards admitting it does not know and leaving the nominative. A registered company name is never declined — the legal form carries the case (spółce z o.o.) and the name matches the KRS entry character for character. A template that needs an opposing party refuses to render without one rather than inventing a defendant. -
services/fees.pyholds legal data with a shelf life. The fee schedules are plain data with the statute on every bracket, so a lawyer can check the table without reading Python. Every response carriesschedule_version,sourcesandverify_note, and the UI shows them — a calculator that looks authoritative and is out of date is worse than one that admits it. Court fees round up to a whole złoty because art. 21 u.k.s.c. says so, applied to the payable amount after any fraction, not just the base. -
A rate is resolved, and the resolution explains itself.
rates.resolvewalks matter override → matter card → client card → firm card → house setting, and within a card person → grade → fallback, returning both the rate and a human-readable source. It resolves for the date of the WORK, not today.TimeEntry.rate_minoris a snapshot, so editing a card never re-prices recorded time. When nothing matches the answer is an explicit "no rate", never a silent zero. -
Backups: storage is the source of truth. No index table — archive names carry a UTC timestamp, so list/order/prune never open a file. A backup that exists only if the database agrees it exists is not a backup. The dump is pure Python, not
pg_dump: the container has no postgres client binaries, and depending on one would make restores fail exactly when they matter. Restore runs on themigratorengine — theapprole cannot deleteaudit_logorconflict_check, which is precisely why it cannot be the role that rewrites them. Archives never contain.env, so a leaked archive is not also a credential leak. A process without migrator credentials refuses to restore (MIGRATION_DATABASE_URLempty): that is the long-running backend underdocker-compose.managed-db.ymlby default, and the restore there is the one-shotpython -m app.restorein themigratecontainer. Giving the backend the migrator URL (BACKEND_MIGRATION_DATABASE_URL) is an opt-in, never the default — a network-facing process holding a credential that can rewrite the audit log is what the role split exists to prevent. The console's restore checks before it records its intent. -
Search folds diacritics in SQL, and its counts are permission-filtered too.
services/search.pybuildstranslate(lower(col), 'ąćęłńóśźż', 'acelnoszz')— the same mapping asparties._FOLD, solodzfinds Łódź with nounaccentextension to install and no denormalised copy of every text column. Results go throughauthz.readable_node_ids, and a group's total counts only the rows the reader may see: reporting "3 wyniki" while showing 2 tells the searcher a third exists, which is the one fact a wall exists to hide. Each kind scans at mostSCAN_LIMITrows and says so (truncated) — the console shows200+rather than presenting a capped length as a count. -
A matter with invoices cannot be deleted.
invoice.matter_idcarries no ON DELETE rule on purpose — an invoice is a tax document and must not vanish because someone tidied a folder.nodes.deletestates that rule in words before the database says it as a constraint name. -
A notification e-mail names no client, matter or deadline by default.
email_detailis an instance setting and it starts atminimal: a count and a link. Mail leaves the firm — it sits on a relay, in a mailbox provider's index and on a lock screen — andtajemnica adwokackais not a regime where "Apelacja — Kowalski przeciwko Skarbowi Państwa" belongs in a subject line by default.fullexists for a firm running its own mail server; that is their decision to make deliberately, not ours to make for them quietly. -
E-mail is a sweep over
notification.emailed_at, never a send inside the transaction that wrote the row. An SMTP server that is slow or down must not be able to roll back the reminder engine. One message per recipient per sweep, not one per notification — "reminders escalate, they do not nag" applies to the delivery channel too. A failure leavesemailed_atNULL so the next sweep retries; pastnotify.MAX_AGE_HOURSthe row is stamped as given up on rather than retried forever against a mailbox that is not coming back. Already-read notifications are never mailed. -
Every reminder is idempotent by construction.
notify.pushenforces uniqueness on(recipient_id, dedupe_key)with a database constraint, not a SELECT-then-INSERT, and every reminder names its milestone (deadline:<id>:d7). That is what makes the scheduler safe to run as often as it likes, andPOST /admin/reminders/runsafe to press. Never add a reminder without a dedupe key — the scheduler re-derives the same set every cycle. -
Reminders escalate, they do not nag. Milestones are sparse (14/7/3/1/0 days); an overdue deadline is announced once, then once more after three days to whoever manages the matter — falling back to the owner when they are the only manager, which is most of the market. Daily repetition is how a real warning gets ignored.
-
A wall blocks notifications too. Recipients go through
authz.effective_roleon the matter node. A wall that a notification leaks through is not a wall. That includes the chase for a filed item with no service date, which used to go to every administrator with the subject in the title. -
The KRS API masks the names of natural persons. A board member comes back as
N**********with a PESEL of7**********; verified against three unrelated companies, so it is policy, not an artefact.registers.is_maskeddetects it andofficers_redactedreports it. Never create apartyorparty_linkfrom a masked name — a fake party in the register that decides whether the firm may take a case is the worst possible place to guess. The console tells the user to type the names in by hand. -
A register fills blanks, it does not overwrite.
registers.party_updatesdefaults to filling only empty fields: the firm may have deliberately recorded a correspondence address or a trading name, and silently replacing it throws away work someone did on purpose. Overwriting is available but has to be asked for. -
Register mapping is pure and tested against a captured real response (
tests/fixtures/krs_odpis_aktualny.json). The HTTP lives inintegrations/registers.py, so the mapping never depends on a live government service to be tested. -
App tokens mean the same thing in every module.
SessionKind/TokenScope, the sliding idle renewal and the wholeAuthServicearedredd_core's, so the modules cannot drift by construction. On the platform they share onesessiontable, so a token minted for one module resolves in all of them — it is one credential for one person, which is what one account means, and there is no audience field to narrow it. That makes the prefix (sygna_pat_, set in Sygna'sAuthPolicy) matter more, not less: it is the only thing saying where a leaked credential was minted and whose audit log to read first. Minting lives in Atrium (POST /me/modules/sygna/tokens), because a database role that can INSERT asessionrow can mint a working credential for the administrator; listing and revoking stay here, both covered by the reader tier. Standalone, each app keeps its ownsessiontable and mints its own. Scope is enforced indeps.get_current_userand nowhere else: every authenticated route depends on it, so one check covers all of them and no future route can forget it. -
Cookie-authenticated writes must be same-origin —
deps.refuse_cross_site_write, registered once as an app-wide dependency inmain.py(the decision is core's,dredd_core.cross_site.cross_site_write_refusedsince v0.14.0; the dependency only raises this app's own error), checksSec-Fetch-Siteand, where browsers omit it (plain HTTP, older Safari),OriginagainstHost; a bearer token andCORS_ALLOW_ORIGINSentries are trusted. SameSite=Lax does not stop a same-site sibling from POSTing here with a lawyer's cookie. Never call it per route and never exempt a route: login and logout are covered on purpose. What this guard stopped meaning at one origin, and do not try to "restore" it. With the family at<site>/sygnaand<site>/galena, a page in another module's console is same-origin with this API, so both signals —Sec-Fetch-Site: same-originandOrigin == Host— pass. The guard still blocks a genuinely foreign site, which is what it was written for; it no longer separates one module from another, and nothing Host- or Origin-based can, because they share a host and an origin. The consequence is that an XSS in any of the four consoles can drive all four APIs with the user's cookie, so the defence that carries the weight is per-module CSP and the rule that untrusted bytes never execute in-origin. For the same reason never add an entry toCORS_ALLOW_ORIGINSnow that the family is one origin:deps.pyreturns early for any listed origin, bypassing both signals. -
Seniority lives on
lawyer_profile, notapp_user.app_userisdredd_core's model — Sygna cannot add a column to it, and should not want to: what a person's grade is in a law firm is not something the family's identity table has an opinion about. -
matters.CLEARABLE_FIELDSis the list of fields a user may blank out. Everywhere elseNonemeans "not supplied". Without it, setting a rate override would be a one-way door. -
The shared substrate is a package, not a copy.
dredd-core(private, Apache-2.0) is pinned to a git tag inrequirements.txt, and both applications import it. Neverpip install -e ../dredd-corein a checkout that matters: it shadows the pin, and a local edit to core then changes this application with nothing in the repository recording it — which is exactly the drift SHARED.md used to exist to stop. A core change means a tag bump and a repin in both applications, never a workaround in one.deploy_check.pyasserts the pin is a tag and that CI hasDREDD_CORE_TOKEN. Three files are still genuinely copied (alembic/env.py,db/init/01-roles.sh,scripts/license_gate.py) because none of them is importable code, andshared_check.pystill guards those (env.pyas a documented divergence: Galena's docstring names its own schema, Sygna's names none). -
Never fork
dredd_core.authzto get a policy hook — register an overlay. Core has the seam (register_overlay, v0.7.0) and applies it on every path that answers an access question. It is restrict-only: an overlay may lower or revoke a role, never raise one, and core discards a higher return rather than trusting it. A rule that needs to grant is a permission grant and belongs in the grant table. -
Core stays permissive. Apache-2.0; CI denies GPL/AGPL/SSPL. Copyleft or heavyweight components are optional sidecars, never core.
-
No build step for the console. The one permitted exception is a committed Vite bundle with a working fallback, following Galena's
frontend/static/editor.jsprecedent. -
Console security:
esc()every dynamic value; bearer token in memory only, cookie session primary; nothing loads from a CDN (the CSP has no third-party origins).frame-srcnames Galena's origin only whenGALENA_EMBEDis on. -
No reverse proxy, anywhere. On the platform Atrium's backend is the front door and forwards
/sygna/*here with the prefix stripped (uvicorn's--root-path "$ROOT_PATH"puts it back); standalone,docker-compose.ymlpublishes the backend on :8041 with nothing in front. The backend is its own edge (app/edge.py, wired inmain.py): it serves the console (frontend/,/frontendin the image via thefrontendbuild context) at/LAST, behindConsoleUnlessApi, so/api/*and/healthznever fall to it (unknown → 404 problem, wrong method → 405 +Allow); any other GET for a missing file getsindex.html(the SPA fallback).SecurityHeaders(pure ASGI, outermost) stamps every response, errors included: nosniff, X-Frame-Options,Referrer-Policy: same-origin,Cross-Origin-Opener-Policy: same-origin; the console (not the API —/api/v1/docsis Swagger from a CDN) also gets the CSP andCache-Control: no-cache.FRAME_ANCESTORSis'none'(default, XFO DENY) or'self'(SAMEORIGIN); anything else refuses start-up. No HSTS (this console has never sent one). Also gzip (min 1000 B), a 100 MB request-body cap (BodySizeLimit, 413), and uvicorn--proxy-headers --forwarded-allow-ips "${FORWARDED_ALLOW_IPS:-127.0.0.1}" --no-server-header— those flags live ONLY inbackend/Dockerfile's CMD, never a composecommand:.FORWARDED_ALLOW_IPSis never*(the port is published). Every path comparison readsget_route_path(scope), neverrequest.url.path(ROOT_PATH). -
Icons are Tabler (MIT), path data vendored into the
ICNmap — the same family Galena uses, so the two consoles match in a shared launcher. Never load them from a CDN; see CREDITS.md for the list. -
Brand = Open Color
cyan8#0c8599 (cyan4#3bc9db in dark, where cyan8 is too dim for stroke-weight use). It is confined to identity, not controls: the app mark, icon tiles (.appcard .ai), the avatar, the focus ring. Buttons, nav and toolbar glyphs stay monochrome — brand everything and nothing stands out. Semantic ok/warn/err is a separate axis. This is a deliberate divergence from Galena, whose brand colour touches the app icon only. -
Mobile: the top bar keeps four controls (menu, breadcrumb, record-time, notifications, account). Everything else carries
.js-tooland moves into the account sheet below 880px — nine 30px buttons left the breadcrumb exactly 0 pixels wide. A horizontally scrollingbodyis the one layout bug with no acceptable version; wide tables scroll inside.tablewrap. -
Never transition
visibilityover a duration or with a delay. The off-canvas drawer needs the transition machinery to tick, and when frames are throttled it gets stuck in whichever state it was in.transformtransitions;visibilityflips instantly. -
Counterparty register (dredd-core 0.21.0, revision
0006; the Compass split's K2). Sygna WRITES the platform's one register (counterparty,counterparty_alias,counterparty_contact): standalone in its own schema, on the platform in the identity schema, granted by the hub (COUNTERPARTY_WRITER_ROLES=sygna_app,COUNTERPARTY_MIGRATOR_ROLESincl.sygna_migrator; check with--counterparties writer). A party is not a counterparty:party.counterparty_id(RESTRICT) links an organisation to the one it is; natural persons are never put in the register (GDPR).services/parties.sync_counterpartyruns on create/update: no-op whencounterparties.writable(db)is false, links via corelink_or_create(NIP, KRS, then match_key), afterwards only FILLS empty fields, and a race on a number leaves the party unlinked instead of failing the save.0006backfills unlinked organisations (through the hub's import door on the platform), is idempotent, and its downgrade drops only an empty register. Backups and0001excludeCOUNTERPARTY_TABLESon the platform (models.SHARED_TABLES);assert_identity_schemacovers them.
Gotchas
- On Windows, write
.envwithout a BOM (PowerShellOut-File -Encoding utf8adds one, and pydantic-settings folds it into the first key name) — use[System.IO.File]::WriteAllText(...). - The migration creates enum types then runs
Base.metadata.create_all(enums usecreate_type=False, socreate_allnever emitsCREATE TYPE). Neither a new model nor a new enum needs a migration change any more:dredd_core.schema.create_enum_typesderives the labels from the metadata, so they cannot drift from the models and there is noENUMSmap to forget. NodeKindkeeps Galena'sprojectlabel even though Sygna never writes it: a tree that ever holds both applications' nodes then reads correctly here, and it costs nothing —node.kindis text validated by a registry, not an enum.- Polish name matching lives in
services/parties.py(normalize/_stem/similarity)._stemis a deliberate approximation — it over-matches, which is the right failure direction for a conflict screen. Replacing it with Morfologik (BSD) is the documented upgrade; nothing else depends on how it works.similarityis containment, not Jaccard, so "Kowalski" scores 1.0 against "Kowalski Nowak i Wspólnicy" — acting against one named partner of a firm we act for is exactly the conflict being looked for. models/timelog.py(nottime.py) so the module never shadows the stdlib.- After a change that touches several layers, run
scripts/walkthrough.py. It drives the spine against a running instance and prints what came back. Both times this project found something that mattered it was this way round — a conflict note that contradicted its own hit count, and an upload posting to a path Galena does not serve — and neither had a failing test. A green suite means the assertions somebody wrote still hold, not that the product works. - Syntax-check the console after editing it:
node --check frontend/app.js. A duplicateconstinside one function silently stops the whole file parsing, so every function defined after it disappears — and the symptom is a screen that renders nothing, with no console error to find, because the listener that would have caught it never ran either.
Status
Stage A / Phase 1 complete, plus the correspondence spine, the court-fee calculator,
rate cards, the registers connector, the reminder engine, Phase 3 — money,
complete (August 2026), and dredd-core adoption (September 2026 — identity, the org tree,
authz, auth and the error shapes are an imported package rather than copies), and one platform,
one account (September 2026 — 0003_shared_identity, dredd-core v0.10.0). Verified against a real PostgreSQL 16: migration + seed,
513 tests plus 13 that run only against a live Galena, 162 routes, 32 tables, the
least-privilege grants (app cannot mutate audit_log or delete conflict_check), the licence
gate, scripts/shared_check.py clean against Galena, and every console route rendering with no
JS errors.
One account for the whole platform is rehearsed, not just written (2026-09-24). On a live
PostgreSQL 16 emulating the managed database: a hub owning the shared dredd schema beside Sygna's
own; Sygna migrated and seeded the way the live box is today; provisioning re-run with
--identity-schema; then 0003. It refused by name on the demo account the shared store did not
have, accepted it after the platform-admin import step, moved every one of the 35 person-columns
plus permission_grant.principal_id, kept every row of every table keyed by user (the ethical wall
included), left the sygna schema with no identity table and all 35 foreign keys on
dredd.app_user, and re-ran cleanly on an already-converted database. managed check --identity-tier reader passes as both roles and prints the tier in full. The whole integration
suite then passes against that post-cutover database — 532 passed, 33 skipped — signed in with
a session the HUB minted, which is single sign-on asserted rather than described. The standalone
shape is unchanged: 550 passed, 15 skipped, downgrade base and back up included. CI's
managed-db job now runs the platform shape; the backend job keeps the standalone one.
Per-module permissions land on top of it (2026-09-29, dredd-core v0.11.0). module_moderator
becomes module_permission: the same row, plus a role of user or moderator — and the answer
that did not exist before, no row at all. moderation.assert_may_use in
deps.get_current_user is the whole of the new behaviour: a person the platform has heard of but
who was never given Sygna is now refused at the door instead of shown an empty desk. 0004 is the
migration that reaches the databases 0001 already built under the old core, rehearsed on a real
PostgreSQL 16: a database migrated under v0.10.2 comes out of it shape-identical to a fresh one
(constraints, indexes, columns and grants all compared), every existing row becomes a moderator
because that is what the old table meant, a second run changes nothing, the hand-dropped-table
branch rebuilds it from the metadata with its grants, and downgrade base and back up is clean.
Standalone is untouched by design — core answers "user" for everybody, so the guard admits
everybody — and the live standalone suite says so: 569 passed, 17 skipped against a migrated
and seeded database, 394 passed, 192 skipped DB-free. A user row reaches nothing in the
matter tree and no arrangement of the table crosses an ethical wall: the only tier
dredd_core.authz consults is MODERATOR, and the wall overlay still runs after it.
Two things only a live run could have found, both fixed: the %I in a format() call that would
have put a percent sign in a rendered migration template (the family's rule), and the polymorphic
filter AND principal_type = 'user' whose own quotes closed the surrounding SQL literal —
syntax error at or near "user", on the first real execution. Both have tests now.
ORDERING the operator must get right (it fails at the HUB's migration, not this one): every app
has to be provisioned with --identity-schema before the hub grants any tier, because
shared_identity_grants_sql refuses to grant on a table to a role holding no USAGE on the
schema, and USAGE comes from provisioning. db/managed/README.md §4a has the sequence.
The container stack runs in CI (compose-smoke, 2026-09-12): the image builds, compose brings
postgres → migrate+seed → backend (published on :8041) up in order, and the job logs in through
that port, reads the seeded matters, checks the console's security headers, the SPA fallback and
that an unknown API path is a 404 problem rather than the console, and confirms from inside
the database container that the app role is refused on audit_log and conflict_check. It is
the only place those files execute — the development machine is a VM without nested
virtualization and cannot run containers. Building the image needs DREDD_CORE_TOKEN as a
BuildKit secret, because dredd-core is a private repository; the first draft of this job found
that nobody had been able to build the image since the package was adopted. The KRS and Biała lista connectors were exercised against the live government
services on 2026-08-13.
practice_mode (law_firm | in_house) is an instance setting: an in-house department gets
the same matters, deadlines and conflicts without the billing surface. GET /config carries it
to the console.
The reminder scheduler is an in-process asyncio task in the app lifespan (Galena's backup
-scheduler pattern). In a multi-instance deploy, run it on one instance only —
REMINDERS_ENABLED=false on the others. Duplicate runs are harmless (the dedupe constraint),
but they are wasted work.
The fee schedules in services/fees.py have not been checked against an official text. They
were assembled from working knowledge of the statutes. The arithmetic is tested; the numbers
need a lawyer's eye before anyone relies on them, and the UI says so on every result.
Galena integration has now been exercised against a running Galena (2026-09-12): the probe,
creating a case file, and filing a generated document, end to end. It found a real defect that a
month of green tests had not — Sygna posted to /files/{id}/upload where Galena serves
/projects/{id}/upload, and the stub answered whatever it was asked.
Two tests keep it that way. test_galena_contract.py reads Galena's router table out of its
source and asserts every path Sygna calls exists — no server, no database, skips when Galena is
not checked out beside this repository. test_galena_live.py runs against an actual instance and
is skipped unless SYGNA_GALENA_LIVE=1, GALENA_BASE_URL and SYGNA_GALENA_TEST_TOKEN (an app
token minted in Galena) are all set. The endpoints live in one ENDPOINTS map in
integrations/galena.py so the code and the contract test cannot drift.
GALENA_BASE_URL empty is still a clean no-op.
0001_initial was extended in place with the correspondence table and its enums rather than
adding a revision, because nothing was deployed — the create_all-from-metadata style means a
table added to the model would otherwise be created twice. That stopped with 0002_runtime_grants
(September 2026, the shared managed database): the grants are now dredd-core's, loud and
schema-aware, for DB_APP_ROLE, and new tables need their own revision, ending with the same
runtime_grants_sql call. 0001's own grant block follows DB_APP_ROLE in the current schema
too, and its downgrade drops pgcrypto only when the migrator owns it (it never does locally or at
a managed provider, so the old unconditional drop made every downgrade fail).
The shared managed database is emulated, not yet real (2026-09-15): dredd-core's TEST-ONLY
emulate on PostgreSQL 16 with TLS required, Sygna provisioned beside a second app schema holding
a complete copy of Sygna's tables, migrated over verify-full as its migrator role with a
password full of % @ : / ? #, the whole suite as the runtime role, the managed check with
isolation both ways, and the negative cases (migrating as the admin, a missing DB_APP_ROLE,
sslmode=prefer). CI's managed-db job repeats it on 17 with dredd-core v0.9.0 (the pin). The
provider is never named anywhere in the repository (2026-09-23): db/managed/,
docker-compose.managed-db.yml, MANAGED_DB_CA_FILE, and the family's one TLS rule
(require_verified_tls + DB_LOCAL_HOSTS) replaced Sygna's own DB_REQUIRE_VERIFY_FULL.