Metadata-Version: 2.5
Name: commissura
Version: 0.1.2
Summary: Turn raw clinical material into standardised, de-identified, research-ready datasets
Project-URL: Homepage, https://github.com/jonathanmanca/commissura
Project-URL: Repository, https://github.com/jonathanmanca/commissura
Project-URL: Issues, https://github.com/jonathanmanca/commissura/issues
Project-URL: Changelog, https://github.com/jonathanmanca/commissura/blob/main/CHANGELOG.md
Project-URL: Author, https://www.linkedin.com/in/jonathan-manca/
Author: Jonathan Manca
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: bids,clinical-data,de-identification,dicom,ehds,hl7,pseudonymisation,synthetic-data
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Healthcare Industry
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: pydantic<3.0,>=2.7
Requires-Dist: typer<1.0,>=0.12
Provides-Extra: dev
Requires-Dist: hatchling>=1.27; extra == 'dev'
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pyshacl>=0.26; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: pyyaml>=6.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0; extra == 'dev'
Description-Content-Type: text/markdown

# commissura

[![PyPI](https://img.shields.io/pypi/v/commissura?style=flat-square&logo=pypi&logoColor=white)](https://pypi.org/project/commissura/)
[![Python](https://img.shields.io/pypi/pyversions/commissura?style=flat-square&logo=python&logoColor=white)](https://www.python.org/)
[![CI](https://img.shields.io/github/actions/workflow/status/jonathanmanca/commissura/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/jonathanmanca/commissura/actions/workflows/ci.yml)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=flat-square)](https://github.com/jonathanmanca/commissura/blob/main/LICENSE)
[![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20Windows-lightgrey?style=flat-square)](https://github.com/jonathanmanca/commissura/actions/workflows/ci.yml)
[![Status](https://img.shields.io/badge/status-alpha-orange?style=flat-square)](https://pypi.org/project/commissura/)

Turn raw clinical material — HL7 v2 lab messages, free-text reports, DICOM
imaging metadata — into a standardised, de-identified, research-ready dataset
with a verifiable manifest.

BIDS gives neuroimaging a shared layout. Nothing equivalent links laboratory
results and clinical reports to the same subject. `commissura` builds that bridge.

> **All clinical data in this project is synthetic.** No real patient data ever
> enters this repository, in any form. Every fixture is generated by
> `commissura generate`.

## Why

EU Regulation 2025/327 (European Health Data Space) makes secondary use of
health data a legal obligation for data holders from March 2029. Hospitals,
research institutes and laboratories will have to produce structured,
de-identified, documented datasets. `commissura` is a local command-line tool that
does exactly that — no service to deploy, no network component, no accreditation
required.

## What this will not do for you

Four limits, stated here rather than further down, because a tool that touches
health data should declare them before you install it and not after.

**It needs a structured source beside the free text.** The de-identification
here works by targeted redaction: the laboratory message *states* this patient's
name, national identifier and record number, MSH-4 states the sending
institution, OBR-16 the ordering clinician, the imaging header the institution's
address. So the problem stops being "find the names in the prose" and becomes
"remove these specific strings", which is exact, auditable and countable. Take
the structured source away and the method has nothing to work from. **If what
you have is a folder of PDF reports and nothing else, this tool is not for
you** — you would need named entity recognition, which this project rejects on
the evidence that general-purpose tools miss over half of clinical PHI. Rules
first, measurement always; and no rules are possible without a source of truth.

**Exact intervals are a re-identification channel, and this tool keeps them
exact on purpose.** The dataset carries `day_offset` from each subject's own
baseline, with no calendar anchor, because the interval between two events is
clinically useful and the absolute date is what has to go. The consequence:
anybody who learns **one** true date for a subject from anywhere else — a
discharge letter in a drawer, a dated post, an insurance claim, an obituary —
recovers that subject's entire timeline, because every other event is a known
number of days from it. Blurring the intervals would close the channel and
destroy the clinical value, so this tool does not do it. Decide which side of
that trade-off your release is on before you publish; it is the single most
likely route from this dataset back to a person.

**On a small cohort, k-anonymity does not reach a useful threshold, and no
amount of care changes that.** `risk` reports the number honestly and the
honest number is often 1: twenty-five people with exact ages cannot reach k=5
on age and sex together. That is arithmetic, not a defect in the dataset or the
tool. The fix is banding the ages or dropping an attribute before release, which
is a decision about your data that `commissura` does not take for you. Run
`commissura risk` and read the number before you release anything, and see
[`commissura risk`](#commissura-risk) for why k is a measurement and not a
certificate.

**Lose the key file and the dataset is permanently orphaned.** Not unreadable —
the data stays exactly as useful as it was — but no longer *extensible* or
*linkable*. You cannot add next year's records for the same people, because
their subject labels can never be derived again. You cannot link it to another
dataset you built, because you cannot show the labels came from the same secret.
You cannot answer a question about which original record a row came from. Every
pseudonym in the dataset derives from that one file, nothing in the dataset can
reconstruct it, and that is the design working as intended. Back it up
somewhere you will still have in five years.

## Install

Requires Python 3.11 or newer.

```bash
pip install commissura
```

From a checkout instead, which is what running the tests and the linters needs:

```bash
git clone https://github.com/jonathanmanca/commissura.git
```

```bash
cd commissura && uv venv && uv pip install -e ".[dev]"
```

**What each artefact carries** is asserted by `tests/test_packaging.py` rather
than intended: the wheel is the package, its typing marker and the two licence
files and nothing else, while the source distribution additionally carries the
tests and the vendored SHACL shapes — so the HealthDCAT-AP conformance claim is
checkable from the archive alone, with no clone and without fetching the
profile's shapes from a server nobody here controls. Measured against the
published 0.1.0 rather than asserted: unpack it, install the development
extras, and the conformance tests pass.

**Releases are started by hand, and checked before they leave.** The same
workflow that uploads a release first runs the whole suite, builds both
artefacts, and installs the wheel into an environment that has never seen this
source tree to drive it end to end on Python 3.11, the declared floor.
`.github/workflows/publish.yml` uses trusted publishing, so no upload token is
stored anywhere here; it has no tag and no release trigger, and a test asserts
there is not. PyPI refuses to re-upload a filename it has already accepted and
a yanked release stays downloadable by exact version, so a release is the one
thing this project cannot take back.

## The whole thing, start to finish

Five commands. Every output below was captured from a real run, not written by
hand. A test re-runs this walkthrough and compares each block against what the
command prints, so a capture cannot quietly go stale — which it did three times
before the test existed. Lines showing a key fingerprint or a `sub-` label are
the exception: they come from a key that is not in this repository.

### 1. Make a key

```bash
commissura keygen --out ./commissura.key
```

```
Wrote a new key to commissura.key
  fingerprint        35eea6fcd0bad4df
  owner-only access  NO

  This platform does not honour POSIX file modes, so the key file inherits the
  directory's permissions. Move it somewhere only you can read, or keep it in an
  encrypted store. Back it up: every dataset built with it becomes permanently
  unlinkable if it is lost.
```

Every pseudonym derives from this one secret. The key is never printed and never
enters the dataset; what gets recorded is the fingerprint. On Linux and macOS the
file is created mode 0600 and the message says so instead.

### 2. Make something to work on

```bash
commissura generate --subjects 25 --seed 42 --defect-rate 0.2 --out ./raw
```

```
Wrote 190 files to ./raw
  lab          115  HL7 v2 ORU^R01 messages
  cda            0  HL7 Italia CDA R2 documents
  reports       48  free-text documents
  imaging       27  DICOM JSON Model sidecars

  subjects      25  seed 42
  PHI spans   3628  recorded as ground truth
  defects      366  injected at rate 0.2

  Verified: every recorded PHI offset matches the file on disk.
```

Three separate exports, as a hospital would hand them over, with 366 injected
defects and 3,628 identifiers whose exact character positions are on record.

### 3. Build the dataset

```bash
commissura build ./raw --out ./dataset --key-file ./commissura.key \
    --hdab "Agenzia Nazionale Sintetica per i Dati Sanitari" \
    --publisher "IRCCS SINTETICO MAREBIANCO" \
    --contact-point "dati@irccs-sintetico.invalid" \
    --access-url "https://portale-hdab-sintetico.invalid/permessi"
```

```
Wrote 211 files to ./dataset
  subjects       25  sessions 90
  lab            94  tables and sidecars
  reports        90  documents and sidecars
  imaging        27  metadata sidecars in derivatives/

  key fingerprint        35eea6fcd0bad4df
  free-text redactions   528
  participant ages       exact, truncated at 89
  linkage issues         49
  records dropped        3  (no readable date)
    reports/5806125_rad_1.txt  (undated_record)
    reports/2935320_dim_5.txt  (undated_record)
    reports/5247115_dim_2.txt  (undated_record)
    lab/0976285_LAB55466956.hl7  (conflicting_identity: this record shares an
      identifier with a record naming a different person; both identities are
      kept so that both names are redacted)
... nine more of the same ...
    ... and 39 more linkage issue(s)
  minimum k              1  (21 combination(s) below 5)
  profile                HealthDCAT-AP 8, non-public tier

  Residual risk the method cannot reach:
    1 unrecognised all-capitals token(s) remain, of 5 characters. Nothing
    declared them, so this is the layer that catches what was not
    anticipated. Not quoted here: this report travels with the dataset.

  Validation: conforms - 0 error(s), 8 warning(s)
```

**Three of the forty-eight reports are not in the dataset**, and that is the
walkthrough earning its keep rather than a disappointment. At this defect rate
the generator leaves some report dates as an unfilled template placeholder —
`Data del referto: __/__/____` — and a session is a dated encounter, so those
documents link to a person and then have nowhere to go. They used to vanish
without a word. Now the count is on the second screen you look at and the paths
are listed under it.

**`linkage issues 49` is the line to read next, and forty-nine is not a
failure.** A reason either means a record could not be attached to anybody or
it means the record was attached and something about the attribution is worth a
second look — here they are all the second kind. The manifest counts the two
separately, because adding them together would be a false statement about what
the dataset contains. See
[the manifest](#linkage-is-accountable) for the split.

Two of the three reasons are defects injected on purpose,
`lab.conflicting_identity` and `reports.wrong_patient_name`. **The third is not
a defect at all**: one of the five generated sites has a laboratory feed whose
source system holds no national-identifier field, so every message from it
carries a placeholder where the codice fiscale belongs. Those records are
attached by the record number *within that institution*, which is what
`invalid_national_identifier` says on the terminal, naming the institution so
you know whose export to go and ask about. That is a real export, not damaged
data — which is why it is a property of the site and appears even at
`--defect-rate 0`.

It also means the walkthrough's dataset holds subjects keyed on something other
than a codice fiscale, which is the case
[acting on an opt-out](#acting-on-an-opt-out) needs a different kind of entry
to reach.

The four `--hdab`, `--publisher`, `--contact-point` and `--access-url` values
have no defaults, because they are facts about your release arrangement and the
tool will not invent them. Leave them out and it still builds, and tells you
what is missing. The one warning left at the end is `--license`, for the same
reason: see [conformance](#conformance-is-checked-against-the-profiles-own-shapes).

### 4. Check it

```bash
commissura validate ./dataset
```

```
WARNING DI009: derivatives/imaging-metadata/sub-744ee679b207_...json
               records BurnedInAnnotation=YES
        Identifiers may be rendered into the image itself. This tool does
        not inspect pixel data, so they are still there. Remove or redact
        the pixels before release.
... six more of the same ...
WARNING DS005: dataset_description.json does not record 'License'
        Recommended so the dataset can state its own provenance.

CONFORMANT: 0 error(s), 8 warning(s), 0 notice(s) from 40 rules
```

`build` already ran this and would have failed if it did not conform. Running it
separately is for datasets you did not build here.

**Seven of the eight warnings are the dataset telling you something true about
itself** — the eighth is the missing `License`, which the build section above
explains. Seven of its twenty-seven imaging studies say in their own metadata
that
identifiers are rendered into the pixels — put there by the
`imaging.burned_in_annotation` defect, which is what a real scanner does when a
technician types a name onto a screen capture. This tool orchestrates `dcm2bids`
rather than reading pixel data, so it cannot remove them, and the flag is
carried on purpose so that whatever converts the images knows to look.

A warning rather than an error, because the dataset is not malformed and
refusing to build would leave you worse off than telling you. It is a warning
rather than silence because a dataset nobody warned about is one somebody
converts without looking — which is how it behaved until the audit of
2026-11-13 found `conforms — 0 warnings` printed over a dataset in which every
study was flagged.

### 5. Read the risk

```bash
commissura risk ./dataset
```

```
  participants           25
  quasi-identifiers      age, sex
  minimum k              1
  below k=5              21 combination(s)
    k=1  age=22, sex=M
    k=1  age=26, sex=F
... eight more rows, then the laboratory-values section ...
```

Twenty-one of twenty-five participants are unique on age and sex together. That
is not a defect — twenty-five people with exact ages cannot reach k=5 on two
attributes — and it is the number an access body would ask you to fix by banding
the ages before release. The command reports it rather than passing judgement.

You can act on it. `build --age-band 10` writes `40-49` instead of `42` and
takes the same cohort from twenty-one combinations below the threshold to ten;
see [generalising ages](#generalising-ages) for the width, which is yours to
choose.

### What came out

```
dataset/
  dataset_description.json      BIDS
  healthdcat-ap.jsonld          EHDS Article 77, for the access body
  participants.tsv              participant_id, age, sex
  participants.json
  sub-0366506f1824/
    ses-01/ ses-02/
      lab/      sub-..._ses-01_lab.tsv  + .json
      reports/  sub-..._ses-02_run-01_report.txt + .json
  derivatives/imaging-metadata/
  .deident/
    manifest.json               what was done, and what it could not reach
    risk_report.json
```

And one report, before and after. Same document, same patient:

```
IRCCS SINTETICO MAREBIANCO                           [INSTITUTION]
Via dei Glicini 35 - Milano                          [ADDRESS] - [ADDRESS]

REFERTO DI DIAGNOSTICA PER IMMAGINI                  REFERTO DI DIAGNOSTICA PER IMMAGINI
===================================                  ===================================

Paziente: GIULIA FERRARA                             Paziente: [NAME]
Nato/a il: 15/07/1950   Eta: 72 anni                 Nato/a il: [BIRTH-DATE]   Eta: 72 anni
Codice fiscale: FRRGLI50L55X959F                     Codice fiscale: [NATIONAL-ID]
Numero nosografico: 8975172                          Numero nosografico: [PATIENT-ID]
Data del referto: 26/08/2022                         Data del referto: [day_offset:+3]
```

`reports/8975172_rad_1.txt` became
`sub-0366506f1824/ses-02/reports/sub-0366506f1824_ses-02_run-01_report.txt`.

Four things to notice. The clinical question survives word for word — a scrubber
that removed the medicine would protect a useless dataset. The **age stays**,
because 22 is clinically useful and not identifying on its own, while the
**birth date is removed rather than offset**, since an offset from the subject's
own baseline would state it exactly. The report date became an offset, so the
interval to every other event in this subject's record is still exact. And the
subject label `sub-0366506f1824` is the same label this person carries in the
lab branch and in the imaging metadata, which is the only thing tying the three
together.

## Who a record belongs to

Everything downstream of this question depends on the answer, and nothing
downstream can tell when it is wrong. Targeted redaction removes the identifiers
your structured exports *declared for that subject*, so two people grouped under
one key leave only one set of identifiers to remove — and the other person's name
is never looked for. The policy is in
[`read/identity.py`](https://github.com/jonathanmanca/commissura/blob/main/src/commissura/read/identity.py), which states its own
reasoning; the shape of it is:

**A subject is established by a validated national identifier, or by a record
number scoped to the institution that issued it.** The manifest says which, per
dataset, under `source.subject_keys`:

```json
"subject_keys": { "national_id": 25, "scoped_record_number": 0 }
```

A subject on the first kind is relinkable to another holder's export under the
same key. One on the second is not — a hospital's record number means nothing
outside it — so that number is worth looking at before you release.

**A missing identifier is never a shared one.** `UNKNOWN`, `N/A`, a row of
zeros, a wrong check character, the wrong length: each is reported by name and
none is ever an identity key. If your export fills an unavailable codice fiscale
with a sentinel, those records are keyed on their record numbers instead and you
get one `invalid_national_identifier` issue per record saying so.

**A record number is scoped to its assigning authority**, read from PID-3
component 4, or MSH-4, or DICOM `InstitutionName`. Two hospitals both number
their patients from 1, so an unscoped index attributes one site's imaging study
to another site's patient. Where one number is used by two people and the
authority cannot tell them apart, every record resolving through it is reported
as `ambiguous_record_number` rather than attached to a guess.

**What a report's header declares is removed too, and a disagreement is
reported.** A laboratory message states the patient in PID-5; a report states
them in its own header, and the two can disagree — a mis-filed document, which
happens in any export. Both now reach redaction, so a report naming somebody
else does not publish that name. And when the name shares no word with any name
the subject is known by, you get a `conflicting_report_name` issue, because a
name that disagrees can mean the document belongs to a different patient and no
amount of redacting makes that right.

The comparison is on the *set* of words, folded, so `ROSSI MARIO` against
`MARIO ROSSI` is not a conflict and nor is an abbreviated given name, a middle
name present in one source only, or a surname written with and without its
space. Each of those is one person recorded twice far more often than two
people confused, and crying wolf on them would bury the case the check exists
for.

**The codice fiscale is validated, including omocodia.** When two people would
be assigned the same code the Agenzia delle Entrate substitutes letters for
digits, so a validator that only checks the checksum rejects genuine
identifiers. Any other national scheme — an ENI or STP code, another country's
identifier — fails validation and falls back to a scoped record number. That is
a real limitation and is why `subject_keys` is in the manifest.

## Bringing your own data

Nothing in `build` depends on the generator. `read_corpus` does four globs and
reads whatever it finds, so a corpus exported from a real system works — if it
is laid out the way the reader looks for it, and if the documents carry the
identity the linkage needs.

```
raw/
  lab/        *.hl7    HL7 v2 messages, one per file
  cda/        *.xml    HL7 Italia CDA R2 documents, one per file
  reports/    *.txt    free text, UTF-8
  imaging/    *.json   DICOM JSON Model (PS3.18) metadata, one array per study
```

Those four patterns are the whole contract. None of the directories is
required — hand over what you have. Subdirectories are not searched, other
extensions are ignored, and the `_generator/` directory a generated corpus
carries is only read by `commissura measure`.

**If you have a choice, send CDA.** `lab/` and `cda/` are two forms of the same
thing, and the plain-text `reports/` path needs your template's header labels to
match a table inside this tool. A CDA document states the patient's identity in
defined elements instead, so there is nothing to match and nothing to get
quietly wrong. The section below says what that does and does not buy you.

### What each kind of file has to carry

**A laboratory message establishes a subject, so it needs an identity.** The
reader wants a national identifier: in the PID-3 identifier list with type code
`NNITA` or `NI`, or failing that in PID-19. A message with neither is reported
as `unreadable_lab_message` and the person it describes does not exist as far
as the rest of the run is concerned. PID-3 with type code `MR` supplies the
record number, which is the only thing imaging can be linked on. The rest is
read where present and skipped where not: MSH-4 the sending facility, OBR-4 the
panel, OBR-7 the collection time, OBR-16 the ordering clinician, OBX the
results.

**A report is linked by the labels in its header.** Lines of the form
`Label: value`, matched exactly:

| Label | Used for |
| --- | --- |
| `Codice fiscale` | the national identifier — tried first |
| `Numero nosografico` | the record number — the fallback |
| `Data del referto` | which session the report belongs to |
| `Paziente` | the patient's name, so the scrubber can remove it |

A line reading `Dott. SURNAME NAME` is taken as the signature, and it is the
**only** structured source for the report's author: no laboratory message names
the clinician who wrote a report, so without it that name cannot be redacted
anywhere it appears.

**Imaging is linked on `(0010,0020)` PatientID**, compared to the record number
with leading zeros stripped. `(0008,0020)` StudyDate decides the session.

Dates are accepted as `YYYYMMDD`, `YYYYMMDDHHMM`, `YYYYMMDDHHMMSS`,
`DD/MM/YYYY`, `DD.MM.YYYY` or `YYYY-MM-DD`.

### HL7 Italia CDA R2 laboratory reports

`cda/*.xml` is read against *Specifiche HL7 CDA R2 del Referto di Medicina di
Laboratorio v.1.3*, one of the national document standards the Ministry
publishes with HL7 Italia and AgID. A laboratory document produces two records
— the LOINC-coded results and the human-readable narrative — so it replaces a
`lab/*.hl7` message and a `reports/*.txt` file together, and nothing downstream
changes.

**The reader needs no profile table**, which is why the three other profiles
cost it nothing: a document whose code is not the laboratory one yields a
report record alone, and the identity header is read the same way for all four.
It is the header, not the document type, that the four profiles share.

What the reader takes, and where each value comes from:

| Element | Used for |
| --- | --- |
| `recordTarget/patientRole/id` | the patient's identity, by the OID in `@root` |
| `patient/name/family`, `given` | the name, stated separately and never guessed |
| `patient/birthTime`, `administrativeGenderCode` | the participant row |
| `componentOf/encompassingEncounter/id` | the numero nosologico — what imaging links on |
| `custodian/.../representedCustodianOrganization/name` | the institution, and the scope of that record number |
| `legalAuthenticator/.../assignedPerson/name` | who signed it |
| `author/.../assignedPerson/name` | who wrote it |
| `ClinicalDocument/effectiveTime` | which session the document belongs to |
| `section/code` | the laboratory specialty, in the `panel_code` column |
| `section/text` | the narrative, which goes through the scrubber |
| `observation/code`, `value`, `referenceRange` | the results |

**Five kinds of patient identifier, because the specification allows five.** The
codice fiscale under `2.16.840.1.113883.2.9.4.3.2` is the ordinary case and is
obligatory for anyone enrolled in the SSN. A patient insured abroad carries two
TEAM identifiers, and only the personal one keys a subject — a card is reissued,
a person is not. An ENI or STP code is sixteen characters beginning `ENI` or
`STP`, and its OID is national *or* the local one of whichever organisation
issued it, so the reader recognises those by the prefix the specification
requires rather than by a namespace it cannot know. An ANA code uses one fixed
OID. Anything else is keyed within the namespace the document names, never
merged into the national one. `.deident/manifest.json` reports which kind
established each subject, under `source.subject_keys`.

**One warning you may see, and it is worth acting on.** The specification's own
worked example prints the codice fiscale root with an extra `.2`:
`2.16.840.1.113883.2.9.2.4.3.2`. If your export was built from that example
rather than from the table three lines above it, every document is reported as
`misdeclared_identifier_namespace`. The reader still links the patient, provided
the same element names the Ministero dell'Economia e delle Finanze as its
assigning authority — but fix the export, because that OID lies in HL7 Italia's
regional and organisation arc and could be somebody's real local namespace.

**What CDA does not do is remove the free text.** Chapter 5.1 of the
specification is titled "human-readable body", and the narrative inside
`section/text` is written by a person. So the scrubber, the residual-risk list
and `commissura measure` all still apply, and so does everything below about
what targeted redaction can and cannot reach. What disappears is having to
guess which line of a template holds the codice fiscale.

A document that declares a DTD is refused. CDA R2 is defined by an XML Schema
and has no use for one, while `xml.etree.ElementTree` expands internal entities
— so a document carrying a DTD is a denial of service rather than a report.

To see the whole thing on CDA input, generate a corpus in that form:

```bash
commissura generate --out raw-cda --subjects 25 --seed 42 --defect-rate 0.2 --cda
```

### The two silent failures, and how to see them

**Labels the reader does not recognise mean every report is unlinked.** If your
template writes `Paziente / Patient` or `CF` or nothing at all, no report
attaches to anybody, every one of them is reported as `unlinked_report`, and
the dataset builds successfully with no reports in it. That reads as "the tool
does not work" and is in fact the tool telling you precisely what is wrong, in
a place you have not looked yet.

**A linked record with no readable date is dropped too**, and that one used to
be genuinely silent. Sessions are dated encounters, so a report whose
`Data del referto` cannot be parsed, or an imaging study with no StudyDate, has
nowhere to go. It is not a linkage issue, because linkage succeeded — so until
this was fixed nothing said anything at all, and the only evidence was a file
count lower than the number of files you handed over.

Both are now counted where you will see them. On a clean export both are zero;
the walkthrough above shows 49 and 3, because its corpus has defects injected on
purpose:

```
  linkage issues         0
  records dropped        0  (no readable date)
```

**The paths are printed by `build` and nowhere else.** An export names its
files after the record they hold, so `lab/6895111_LAB17546198.hl7` carries a
medical record number in its name, and a list of them is a list of patient
identifiers. `.deident/manifest.json` is written to be sent to an access body,
so it counts them by reason instead — `source.linkage_issues` for records that
could not be attached to anybody, `source.records_dropped` for records that
were attached and then had nowhere to go, and
`source.records_not_in_dataset` adding them up, together with
`source.opt_out.records_excluded` for records left out because their subject
[objected](#acting-on-an-opt-out). Separate lists rather than one because they
need different fixes: the first is a labelling problem in your export, the
second a date format the reader does not recognise, and the third is not a
problem at all. Your terminal gets the filenames; the document that travels
gets the counts.

**All forty-nine of those linkage issues are records that *are* in the dataset.**
A reason either means the record could not be attached to anybody, or it means
the record was attached and something about the attribution is worth a second
look. The two are counted separately, because adding them together is a false
statement about what the dataset contains:

```json
"linkage_issues": [
  { "reason": "conflicting_identity",        "count": 17 },
  { "reason": "conflicting_report_name",     "count": 12 },
  { "reason": "invalid_national_identifier", "count": 20 }
],
"records_dropped":            [ { "reason": "undated_record", "count": 3 } ],
"records_not_in_dataset":     3,
"records_flagged_in_dataset": 49
```

`conflicting_identity` means two laboratory messages carry one codice fiscale
with different family names — a mistyped identifier at reception, or one copied
from another record. `conflicting_report_name` means a report's header names
somebody other than the subject its identifiers resolve to: a document attached
to the wrong record, or a template filled in over the previous report. Both
records stay in the dataset and both names are redacted; what you are told is
that the attribution is suspect, which is a thing no amount of redacting fixes.

Those two come from the `lab.conflicting_identity` and
`reports.wrong_patient_name` defects, injected at the walkthrough's rate. Before
they existed the corpus reported zero conflicts — not because the data was clean
but because the generator could not produce one, which left the whole path
untested end to end.

`invalid_national_identifier` is the largest group of the three and **is not a
defect at all.** One of the generated sites does not send a codice fiscale: its
PID-3 carries the literal `UNKNOWN`, which is what a real interface writes when
the field is unavailable. Those records are attached by their record number
within the institution that issued it, which is why they are reported rather
than refused — and why they appear at `--defect-rate 0` as well. What the
reason tells you is that those subjects cannot be linked to another holder's
dataset, because an institution's own number means nothing outside it.

A dropped record carries one of two reasons. `undated_record` names the field
that should have held a date. `subject_has_no_dated_event` is worse and is
reported separately for that reason: nothing in that person's records carries a
readable date, so there is no baseline to express offsets from, *every* one of
their records drops — and a row still appears in `participants.tsv`, so the
dataset claims a participant it holds nothing for.

The labels live in one table, `_REPORT_LABELS` in
[`read/corpus.py`](https://github.com/jonathanmanca/commissura/blob/main/src/commissura/read/corpus.py), for exactly this reason:
adapting to another hospital's template is an edit there rather than a rewrite
of the reader.

## Commands

| Command | What it does | Status |
| --- | --- | --- |
| `commissura generate` | Write a synthetic raw clinical corpus, with injectable defects and ground-truth PHI annotations | available |
| `commissura defects` | List the defects the generator can inject, and the real-world cause of each | available |
| `commissura validate` | Check a dataset against the layout and report what is missing | available |
| `commissura rules` | List every validation rule and what it checks | available |
| `commissura keygen` | Create a pseudonymisation key | available |
| `commissura key-info` | Show a key's fingerprint, without revealing the key | available |
| `commissura build` | Pseudonymise a raw corpus into a dataset, with manifest and HealthDCAT-AP description | available |
| `commissura risk` | k-anonymity over participant attributes, flagging k < 5 | available |
| `commissura verify` | Recompute every file's digest and report what changed since the build | available |
| `commissura measure` | Compare the generator's ground truth against the built dataset | available |
| `commissura whois` | Derive the subject label a real identifier was given | available |

Every command that reports anything accepts `--json`, so the tool composes
inside somebody else's pipeline without being screen-scraped.

A test pins this table against the names the CLI actually registers — both
directions, so a command missing from it fails and a row claiming one that does
not exist fails too. A table that lists what the tool does is worth nothing if
it can quietly stop being true, and this one went stale once in the document it
used to live in.

### `commissura generate`

```bash
commissura generate --subjects 25 --seed 42 --out ./raw
```

Produces a corpus that looks like three separate hospital exports, because that
is how such data actually arrives — and linking them is the problem this project
exists to solve:

```
raw/
  lab/        ORU^R01 messages, one file per panel
  reports/    free-text radiology and discharge reports
  imaging/    DICOM-style metadata sidecars
  _generator/
    generation_manifest.json   seed, counts, tool versions, defects applied
    phi_annotations.json       every identifier, with file and character offsets
```

`--cda` writes **everything** as HL7 Italia CDA R2 documents in `cda/` instead
of HL7 v2 messages in `lab/` and plain text in `reports/`, which is the corpus
a site that has migrated to the Fascicolo Sanitario Elettronico would hand
over. **Every document profile the Ministry's index publishes for the three
modalities this tool reads**, each with its own LOINC document code:

| Document | Code | Specification |
| --- | --- | --- |
| Referto di Medicina di Laboratorio | `11502-2` | `HL7IT-IG_CDA2_RefertoMedicinaLab-v1.3-S` |
| Referto di Radiologia | `68604-8` | `HL7IT-IG_CDA2_RAD-v1.1-S` |
| Lettera di Dimissione Ospedaliera | `34105-7` | `HL7IT-IG_CDA2_LDO-v1.2-S` |
| Referto di Anatomia Patologica | `11526-1` | ART-DECOR RAP v1.0 |
| Referto di Specialistica Ambulatoriale | `11488-4` | ART-DECOR RSA v1.1 |
| Profilo Sanitario Sintetico | `60591-5` | ART-DECOR PSS v1.5 |

Off by default, so a given seed produces the same corpus it produced before the
flag existed.

The four narrative profiles share one header, element for element, and differ in
the document code above, the title, the template identifier, which LOINC-coded
sections the body carries, and two values below. **A laboratory report yields
structured results and a narrative; the other four are narrative only** — every
one of those specifications keeps the coded entries optional and says a document
with sections and no entries is still well formed, and a radiology report's
content *is* prose. So a narrative document contributes a report record and no
laboratory record, rather than an empty table claiming the modality carried
something.

Each profile marks its own sections required, and the numbers are not close:
radiology two of eleven, the discharge letter three of sixteen, pathology two of
nine, the outpatient report two of twelve. All of them are emitted, plus the
optional ones the generator has content for. The sections are written in each
template's own order, because `structuredBody` is a sequence — a body whose
sections are each correct and reordered does not validate.

Two header values are per profile rather than shared, and the second is a
finding rather than a difference. **`setId` and `versionNumber`** are written
only for the outpatient report, whose template requires `setId` at 1..1 where
the others leave it optional. And **`typeId/@extension`** is
`POCD_MT000040UV02` for pathology, outpatient and the patient summary — all
three fix it in their own templates — against `POCD_HD000040` for the
laboratory report and the discharge letter. The radiology specification states
no value at all: its single example reads `[POCD_HDXXXXX]`, a placeholder it
never instantiates, so what this tool emits there comes from its neighbours.

**Pathology and outpatient reports are written as CDA and never as free text.**
Both are published CDA profiles; a free-text template for either would be a
layout invented here, which measures nothing the published form does not. The
plain-text path stays exactly as it was, which is also why none of the numbers
captured above moved.

**The patient summary is the one that does not fit that pattern**, and it is
one per subject rather than one per encounter, because it is a document that is
kept up to date rather than a record of an event. It differs from the four
narrative profiles in that there is **no `componentOf`**, so no numero
nosologico — a subject established only by a summary is keyed on their codice
fiscale or on nothing — with `documentationOf/serviceEvent` in its place, and
in that **no section is mandatory** at all.

A generated summary carries an allergies section and a medication section, each
able to say "nothing known" — which the specification treats as a distinct
case from the section being absent, with a template of its own. It does **not**
carry a vaccinations section, and the reason is a defect in the published
package rather than a simplification here: every spelling the package offers
for that section's `templateId` root reads
`'2.16.840.1.113883.2.9.10.1.4.2.3 '`, with a trailing space inside the
attribute value, in the closed document template's permitted-section list and
in the section's own rules alike. There is therefore no spelling that is both a
well-formed OID and accepted by the package, so the section is left out and the
finding is recorded instead of being papered over. Two more section roots,
`.2.13` and `.2.14`, carry a leading space the same way.

One number worth knowing if you reach for the obvious value: the radiology
document code is **68604-8**, not `18748-4`. The latter is LOINC's "Diagnostic
imaging study" and is what memory produces; section 4.1.5 of the radiology
specification fixes `68604-8` as a constant.

**A CDA corpus also contains patients who hold no codice fiscale**, which an
HL7 one does not. The specification enumerates four other ways a patient is
identified, and a real hospital sees all of them: a **TEAM** card for somebody
insured abroad, an **ENI** code for a European not enrolled in the health
service, an **STP** code for a foreigner temporarily present, and an **ANA**
code. One subject in four is one of these, cycling through the four so a
sixteen-subject corpus covers them all — far more than a real cohort, and for
the same reason one of the five sites sends its national identifier in the
deprecated PID-19: a path no corpus exercises is not covered, whatever the
coverage percentage says.

Three consequences you will see in the output:

- Those subjects appear in the manifest under `subject_keys` as
  `assigned_identifier`, which is neither a national identifier nor an
  institution-scoped record number. An ENI code assigned nationally *is*
  relinkable across Italy, so calling it institution-scoped would understate
  it; it carries no checksum and its namespace may be one region's, so calling
  it national would overstate it.
- **TEAM writes two `id` elements and only one of them keys the patient.** A
  card number identifies a card, which is reissued on expiry or loss, so a
  subject keyed on it would split across a reissue. Both are redacted; only the
  personal number establishes the subject.
- Their reports carry no `Codice fiscale:` line and link on the record number
  instead. Writing the foreign code under that label would state something
  untrue, and writing it under a correct one would break linkage outright,
  because the reader recognises four header labels and `Codice STP` is not
  among them.

These identifiers are synthetic by construction where the format allows it and
only *marked* synthetic where it does not, which is a real difference. TEAM
numbers name a country in ISO 3166-1's user-assigned `XAA`–`XZZ` range, which
the standard undertakes never to allocate — the same guarantee as the codice
fiscale's `X` place code. ENI, STP and ANA codes publish no internal allocation
rule, so there is no range to sit outside of; they carry the literal
`SINTETIC` instead, which says what they are to anybody reading a file but is
a weaker claim and is not dressed up as the other one.

The generated material **deliberately contains synthetic identifiers** — names,
codici fiscali, absolute dates, addresses, referring physicians. That is the
point: you cannot test a de-identifier on data that has nothing to remove.

`phi_annotations.json` is the ground truth. Because the generator records where
it put every identifier, de-identification recall becomes measurable rather than
assumed — which matters, since general-purpose LLM tools have been shown to miss
over half of clinical PHI.

Offsets are character positions into the UTF-8 decoded file, over a half-open
interval, so `text == content[start:end]` always holds. `--verify`, on by
default, re-reads every file from disk and checks it.

#### Reproducibility

The same seed and the same tool version always produce the same corpus, and the
guarantee is stronger than that:

```bash
commissura generate -n 3  --seed 11 -o small
commissura generate -n 30 --seed 11 -o large   # the first 3 subjects are identical
```

Subject *n* does not depend on how many subjects were requested, because each
one is generated from its own stream derived from the master seed. So a bug
report that says "subject 347 has a negative haemoglobin" stays reproducible
from the seed alone, without shipping the corpus.

#### Defect injection

`--defect-rate` controls the probability that any given defect opportunity is
taken. Every injected defect is recorded in the manifest with the file it landed
in, which is what makes validator development measurable: run the validator,
compare what it reported against what was injected, read off the misses.

`--defect-rate 0` produces undamaged data — but not *easy* data. Identifiers
written inside clinical sentences are how reports are written, not a defect, so
they are always present. Anyone who scrubs the header fields of a clean corpus
and scores perfectly has learnt something useful.

### `commissura validate`

```bash
commissura validate ./dataset
```

Reports everything it finds rather than stopping at the first problem. The
question the command answers is *what is missing*, in the plural, and a
validator that answers one item at a time turns a single review into a dozen
round trips.

```
ERROR   DS002 participants.tsv: required file participants.tsv is missing from the dataset root
        Every dataset must carry participants.tsv.
ERROR   DI003 sub-a3f9c21b4e07/ses-01/reports/sub-a3f9c21b4e07_ses-01_run-01_report.txt:
        contains what looks like an absolute date: '12/03/2023'
        A date written inside a sentence is invisible to field-based scrubbing.

NOT CONFORMANT: 2 error(s), 0 warning(s), 0 notice(s) from 40 rules
```

Exits 0 when the dataset conforms and 1 when it does not. Warnings do not affect
the exit code unless `--strict` is passed: a dataset can conform and still have
things worth improving, and a validator that rejects for stylistic reasons gets
switched off.

`commissura rules` prints the whole rule set. **The rule set is the schema** —
there is no separate specification document to drift out of date.

| Prefix | Rules | What they check |
| --- | --- | --- |
| `DS` | 10 | The skeleton: required files, the dataset description, the manifest |
| `PT` | 9 | `participants.tsv`, and its agreement with the directories on disk |
| `NM` | 6 | Directory and file naming, and the BIDS entity grammar |
| `LB` / `RP` | 6 | The `lab` and `reports` datatypes this project adds |
| `DI` | 8 | The de-identification invariants the layout promises |

The `DI` rules are the ones that justify the command existing, and they are
written as *structural* requirements rather than as advice. A dataset carrying a
real calendar date is not weakly de-identified, it is malformed, because the
layout states that time is expressed only as `day_offset` from each subject's
own baseline. Intervals stay exact; the calendar anchor is gone.

`DI003` is the one that earns its keep: it scans report prose, where a date
inside a sentence — *si confronta con il precedente esame del 12/03/2023* — is
invisible to anything that scrubs by field.

#### Written before `build`, on purpose

`validate` exists before the command that produces datasets. That ordering
forces the schema to be precise: the layout lives in one module,
[`commissura/layout.py`](https://github.com/jonathanmanca/commissura/blob/main/src/commissura/layout.py), and the validator is derived
from it, so `build` will have a specification to satisfy instead of defining one
by accident as it goes.

```
dataset/
  dataset_description.json
  participants.tsv
  sub-<label>/ses-<n>/
    anat/ pet/ lab/ reports/
  derivatives/
  .deident/
    manifest.json
    risk_report.json
```

`lab/` and `reports/` are the extension. They follow BIDS naming rather than
inventing new rules, so a BIDS validator will not recognise them and will not be
confused by them either.

### Pseudonymisation

One secret key, everything derives from it, the key never enters the dataset.

```bash
commissura keygen --out ~/.commissura/key
export COMMISSURA_KEY_FILE=~/.commissura/key
```

```
subject_id  = HMAC-SHA256(key, "subject|" + national_id)[:12]   -> sub-a3f9c21b4e07
date_offset = HMAC-SHA256(key, "offset|"  + subject_id) % 730 - 365
dicom_uid   = "2.25." + int(uuid8(HMAC-SHA256(key, "uid|" + original_uid)))
```

Three properties, each with a tempting wrong alternative:

**Keyed, not plain.** `sha256(national_id)` would be useless. A codice fiscale
encodes a name, a birth date, a sex and a place of birth, so the space is small
enough to enumerate: anyone with a candidate list hashes it and reverses the
dataset over a weekend. With an HMAC they need the key.

**Domain-separated.** Every derivation prepends a label naming what is being
derived. Without it, the same string used as a patient id and as an accession
number would produce the same pseudonym, and a value observed in one role could
be replayed in another.

**Deterministic across runs and modalities.** The same person gives the same
`sub-` label today and in three years, in the lab branch and the imaging branch.
That is the only thing linking three separate hospital exports.

Subject labels keep 48 bits of the digest. Collisions are a theoretical concern
rather than a practical one, but the pseudonymiser records what it has issued
and **raises** on a collision rather than silently merging two people.

#### One permit, one set of labels

TEHDAS2 D7.2 puts it in capitals: *pseudonyms MUST NOT be reused across
different data permits.* One key gives one label space for ever, so without
being told otherwise this tool hands the same `sub-` labels to every data user
who ever receives one of your datasets — and two of them, or one secure
environment holding both, can then join two datasets nobody assessed together.

```bash
commissura build ./raw --out ./dataset --permit IT-HDAB-2029-00417
```

```
permit_key = HMAC-SHA256(key, "permit|" + permit_reference)
subject_id = HMAC-SHA256(permit_key, "subject|" + national_id)[:12]
```

Everything derives from the subkey instead: labels, date offsets, DICOM UIDs,
accessions, the manifest's own tag. **You still hold one key in one file** —
nothing about key custody changes, and the root key is not recoverable from a
subkey.

Two consequences worth knowing before you use it:

- **The fingerprint in the manifest becomes the subkey's.** That is the point:
  a fingerprint is how an access body tells whether two datasets are relinkable,
  and under this scheme two datasets for one permit are and two for different
  permits are not. The root key's fingerprint is recorded beside it.
- **`whois` needs the same `--permit`.** Deriving under the wrong scope gives a
  label for nobody, which looks exactly like a person who is not in the dataset.
  Check the printed fingerprint against the manifest's.
  `commissura verify` needs no flag: the dataset records which permit it
  answers, so verification reads it.

It is opt-in, and a build without `--permit` is byte-identical to one from
before the option existed — pinned by a test, because a change to pseudonym
derivation that moved existing datasets would need a migration plan and this one
cannot be reached by accident. The manifest states which of the two you got,
in those words, rather than leaving it to be inferred.

#### Generalising ages

`risk` has always reported that a small cohort cannot reach a useful k and that
banding the ages is the fix. Now it can be applied:

```bash
commissura build ./raw --out ./dataset --age-band 10
```

```
  participant ages       banded, 10 years
  minimum k              1  (10 combination(s) below 5)
```

Twenty-one combinations below the threshold became ten, on the same
twenty-five people. Minimum k is still 1, because some decade-and-sex
combinations hold one person and twenty-five is a small cohort — the command
goes on reporting the number rather than a verdict.

**The width is yours and there is no default.** Five years is the convention,
ten is what a small cohort actually needs, and which one is right depends on
your cohort and on what the permit is for. TEHDAS2 D7.2 asks that an exact age
be used "only when it is indispensable for the research question and cannot be
replaced by age categories" — a judgement about a research question, which this
tool is not in a position to make for you. Omit the option for exact ages.

Bands are anchored at zero, so a width of ten gives decades. Both bounds are
inclusive.

**The band reaches the prose too, and it did not at first.** A report header
reads `Eta: 50-59 anni` when a band is in force and `Eta: 56 anni` when none is.
That was a real leak for two days: `participants.tsv` said `50-59` while the
same subject's own reports said `56`, so **eleven of twelve banded participants
carried their exact age in a dataset whose manifest declared the band** — and
the k improvement above was handed straight back by the documents. Found by a
deliberate pass over every statement the manifest makes. A disclosure control
applied to one representation of a value is not applied at all, and the manifest
will say it was.

**The age ceiling is a separate mechanism and stays on.** Ages above 89 are
`90+` in every dataset this tool writes, banded or not, and a band's upper
bound is clamped to 89 so the two cannot interfere — a width of seven would
otherwise put an 85-year-old in `84-90` and state that they might be 90, which
is the thing the ceiling exists to prevent. `.deident/manifest.json` reports
them under separate keys for the same reason: one is an invariant, the other is
your choice.

```json
"generalisation": {
  "age": {
    "banded": true,
    "band_years": 10,
    "band_format": "low-high, both bounds inclusive",
    "ceiling_years": 89,
    "above_ceiling": "90+"
  }
}
```

A dataset whose ages read `40-49` is not self-describing: nobody can tell a
decade from a five-year band that happens to start on a multiple of ten, nor a
banded dataset from one whose source only ever carried bands. **An unbanded
build says so just as plainly**, with `"banded": false`, because a reader has to
be able to tell a decision from a silence.

#### Acting on an opt-out

EHDS Article 71 lets a person object to the secondary use of their data, and
TEHDAS2 D6.1 marks acting on it *Mandatory* for a data holder: *identify and
remove data of natural persons who opted-out.* Put them in a file, one per
line:

```bash
commissura build ./raw --out ./dataset --exclude-subjects ./objections.txt
```

```
# received 2026-03-04, ticket 1198
RSSMRA80A01X000Z
VRDLGU75D12X842T

# somebody with no codice fiscale: name the kind of key instead
scoped_record_number|OSPEDALE SINTETICO DI COLLEVERDE|8975172
assigned_identifier|2.16.840.1.113883.2.9.4.3.4|STP0000000SINTETIC
```

Every record belonging to those people is left out: no subject directory, no
row in `participants.tsv`, no pseudonym issued. Everybody else's labels,
offsets and redactions are **byte-identical** to a build without the file, so
acting on one person's objection does not hand your data user a dataset that no
longer joins to the one they already have.

**Never subject labels**, and that is deliberate. A label is derived from your
key and, with `--permit`, from the permit too, so a file of labels is valid for
exactly one of each and silently matches nobody under any other — while an
objection is permanent and a key can be rotated. And a codice fiscale carries a
check character, so a typo is refused by name; twelve hex characters are twelve
hex characters, and a holder who mistypes one would see a successful build and
would not have acted on the objection.

**A bare line is a codice fiscale.** A subject your corpus keyed on something
else is named by declaring the kind: `scoped_record_number|authority|number` for
an institution's own record number, `assigned_identifier|oid|code` for an ENI,
STP or ANA code. The authority is never guessed, because two hospitals' record
numbers are deliberately not one namespace — `0012345` at one and `0012345` at
another are two people. Write the institution as your own exports name it;
spacing, case and leading zeros are normalised for you, and the kinds are the
same ones `source.subject_keys` in the manifest reports, so you can see which
are in play before writing a line.

A line declares its kind rather than having one guessed from the shape of its
value. That distinction is the whole reason this is safe to offer: a guesser
reads a file in the wrong mode and excludes nobody, which is the failure that
looks like success.

**A malformed entry fails the build. An entry matching nobody does not.** The
first cannot be anything but a mistake. The second can mean the person simply
has no records in this export, and no tool can tell that from a mistyped
identifier — so it is reported rather than decided for you:

```
  Opt-out exclusions:
    identifiers on the list           2
    subjects excluded                 1
    records excluded                  7
    matching no subject here          1
      VRDLGU75D12X842T
      An entry matches nothing when the person has no records in this export,
      or when it is mistyped. This tool cannot tell which.
```

Two things worth knowing, both reported rather than left to be found:

- **You have to know which kind of key your corpus used.** When a message
  carries no usable codice fiscale the subject is keyed on the institution's own
  record number, and an ENI, STP or ANA patient has no codice fiscale at all. So
  `build` tells you how many subjects of each kind this corpus holds, and how
  many entries of each kind your list names — because a list naming none of a
  kind the corpus is full of is a list aimed at the wrong population, and that
  is worth seeing before the dataset goes out rather than after.
- **The identifiers are on your disk and nowhere else.** The manifest records
  counts and never a value: a list of excluded subjects is a list of people who
  exercised a right to object, and that document is written to be sent to an
  access body. What it does record is that an exclusion happened at all, and how
  many entries of each kind — which is the point, because a dataset built after
  an objection should not look identical to one built before it, and an auditor
  cannot otherwise tell whether the list could reach the people in it.

Use [`commissura whois`](#commissura-whois) when you need the other direction:
the label a named person was given, in a dataset you have already released.

#### The key is never a command-line argument

There is no `--key <value>` option, here or anywhere. A key passed as an
argument lands in shell history, in `ps` output for every other user on the
machine, and in the logs of any CI system that runs the command. The only ways
in are a key file and an environment variable naming that file — not holding the
key, since the process environment is readable from `/proc` and gets dumped
wholesale into crash reports.

What is printed and recorded is the key's **fingerprint**: a domain-separated
digest that identifies the key without carrying it. It answers the question
somebody asks years later — were these two datasets built from the same key, and
are they therefore linkable? — without answering what the key is.

On POSIX the key file is created mode 0600. On Windows that mode is largely
ignored, so `keygen` reports `owner-only access NO` and says what to do instead,
rather than implying a protection it did not apply.

#### Two different time mechanisms

| | What it is | Where it appears |
| --- | --- | --- |
| `day_offset` | Integer days from the subject's own baseline. Needs no key — it is a subtraction. | **In the dataset.** The only time representation it carries. |
| `date_offset` | Per-subject ±365-day HMAC shift. Preserves intervals exactly, destroys the calendar anchor. | **Never in the dataset.** For values that must stay a syntactically valid date for a downstream tool, notably DICOM `StudyDate` on the way into `dcm2bids`. |

The shift differs per subject deliberately: one offset for the whole cohort
would preserve cross-subject alignment, and a single known date anywhere would
then unshift everybody.

### `commissura build`

The walkthrough above runs this end to end. In full, with every value the
profile requires and the tool will not invent:

```bash
commissura build ./raw --out ./dataset --key-file ~/.commissura/key \
    --hdab "<the access body governing this dataset>" \
    --publisher "<your organisation>" \
    --contact-point "<an address somebody can write to>" \
    --access-url "<where a request for this data would go>" \
    --dataset-type SYNTHETIC_DATA
```

Reads the three exports, links them to the same people, derives every pseudonym
from one key, expresses dates only as offsets from each subject's own earliest
event, scrubs the free text, and writes a BIDS-shaped dataset with two
accompanying documents. Then it validates its own output and fails if the result
does not conform.

#### Free text is de-identified by knowing what to look for

The usual approach to clinical prose is named entity recognition: read the text,
work out which words are names. This does something different, and it is only
possible because the corpus was **linked first**.

The laboratory message states this patient's name, national identifier and
record number. MSH-4 states the sending institution. OBR-16 states the ordering
clinician. The report's own signature line states who signed it. The imaging
metadata states the institution's street address. So the problem stops being
*find the names* and becomes *remove these specific strings* — exact, auditable,
and reportable.

That is the argument for linking modalities before de-identifying them, and the
opposite order is the intuitive one.

A report comes out like this:

```
[INSTITUTION]
[ADDRESS] - [ADDRESS]

REFERTO DI DIAGNOSTICA PER IMMAGINI

Paziente: [NAME]
Nato/a il: [BIRTH-DATE]   Eta: 62 anni
Codice fiscale: [NATIONAL-ID]
Data del referto: [day_offset:+0]

REPERTI
Non segni di sanguinamento intra o extra-assiale.
Si confronta con il precedente esame del [day_offset:-41] eseguito presso [INSTITUTION].
```

The clinical narrative survives intact. The comparison interval survives as an
offset, because *41 days earlier* is clinically useful while *12 March 2023* is
a calendar anchor. **The birth date is removed, not offset**: an offset from the
subject's own baseline would state the birth date exactly in a dataset that also
carries the baseline, which protects nothing.

What the method cannot reach is printed, not scored:

```
  Residual risk the method cannot reach:
    1 unrecognised all-capitals token(s) remain, of 4 characters. Nothing
    declared them, so this is the layer that catches what was not
    anticipated. Not quoted here: this report travels with the dataset.
```

A score invites a reader to treat de-identification as solved above some
threshold. A list tells them where to look.

**Three layers, and only the first is certain.** The detector used to match
``[A-Z]{4,}`` and nothing else, which meant it reported ``FRANCESCA FONTANA``
and said nothing at all about ``Francesca Fontana`` — so a template writing
names in title case would have left a leaked name completely silent.

| Layer | Question | False positives |
| --- | --- | --- |
| Declared values | Did a string we were told to remove survive? | None possible: these were handed to the scrubber by name |
| Position | Is something still sitting where a name is *declared* to be, after ``Paziente:`` or ``Dott.`` ? | Bounded by the label table, not by guessing at names |
| Unanticipated tokens | Is there a word nothing declared that looks like an identifier? | The noisiest layer, and the only one that can see what you did not tell us about |

All three are case-insensitive and accent-insensitive: matching is NFKD-folded,
so ``Fontanà`` and ``FONTANA`` and ``fontana`` are one needle. None of them
quotes what it found, because this list travels in the manifest.

**It is a measurement and not a clearance.** A detector that reports nothing has
reported nothing; it has not established that a document is free of identifiers.
The counterpart is `commissura measure`, which asks the opposite question —
whether the identifiers the generator planted survived — and the two fail
differently on purpose. Layer two depends on a label table, so a hospital
template using labels this tool does not know gets layers one and three only;
that is the same dependency `_REPORT_LABELS` has, now stated rather than
implied.

#### A build publishes exactly what it produced

Everything is assembled in a staging directory beside the destination and moved
into place at the end. So **a rebuild replaces the dataset rather than writing
over it**, which is what makes a withdrawal work:

```bash
# A patient objects. Remove their records from the corpus and rebuild.
rm raw/lab/1787493_* raw/reports/1787493_* raw/imaging/1787493_*
commissura build ./raw --out ./dataset --key-file ./commissura.key \
  --hdab "..." --publisher "..." --contact-point "..." --access-url "..."
```

The withdrawn records are gone from the dataset and from the manifest. Before
this was staged, they were not: the build wrote over what it happened to
overwrite and left the rest, reported `conforms` with exit code 0, and
`commissura verify` then certified the result as `INTACT` for as long as the
dataset existed.

**A destination that is not empty and is not a commissura dataset is refused.**
A directory holding no `.deident/manifest.json` and no
`dataset_description.json` is somebody else's, and there is no flag to override
that — the flag would exist only so that a mistyped `--out` could reach your
documents.

A failed build leaves the destination exactly as it was. Publication itself is
two renames rather than one atomic operation, because no portable call can
rename over a non-empty directory; if the second fails, the previous dataset is
put back and the message says where the finished build is.

**Nothing is removed that this tool did not write.** Both working directories
are created with `mkdtemp` beside the destination — random name, mode `0700`,
atomic — and each carries a marker naming the destination it is for. Every
removal verifies that marker first, so ownership is never established from a
path. A directory without one is refused and left alone, and a working
directory left behind by an interrupted build is visible, named, and says in
its own marker what it was for.

Two builds publishing to the same destination are not serialised: each has its
own working directory and each rename is atomic, so the destination always holds
one *complete* dataset and never a mixture, but which one wins is undefined.
Locking would be the fix if this were a service rather than a command somebody
runs on a folder.

#### Two documents, two readers

| File | Schema | Reader |
| --- | --- | --- |
| `.deident/manifest.json` | This project's own. No standard covers it. | Whoever audits the de-identification |
| `healthdcat-ap.jsonld` | HealthDCAT-AP Release 8, as JSON-LD | A Health Data Access Body, and any catalogue |
| `dataset_description.json` | BIDS | Tools that read the dataset |

HealthDCAT-AP describes a dataset *for a catalogue* — title, theme, access
rights, legal basis, retention period. It carries nothing about what was done to
de-identify the data, so that is a separate document with a separate version.

`--hdab` has no default and is not invented. The profile makes
`healthdcatap:hdab` mandatory at exactly one value, and Italy has not designated
its Health Data Access Body yet, so a dataset naming none is the normal case
until 2027. The command builds anyway and says what is missing:

```
  Not yet conformant. Mandatory properties with no value:
    healthdcatap:hdab
    Supply them with --hdab and --publisher.
```

#### A page to read it with

```bash
commissura build ./raw --out ./dataset --key-file ./commissura.key \
    --hdab "..." --publisher "..." --contact-point "..." --access-url "..." \
    --report ./review.html
```

Everything the dataset records is already on disk, in JSON, for a machine.
Comparing a report before and after de-identification is the one check nobody
can automate — the question is "did the clinical content survive", and a
scrubber that removed the medicine would protect a useless dataset — and until
now it meant opening two files in two windows and reading across. `--report`
writes a single self-contained HTML page: the build summary, a few reports side
by side, redaction counts by category, the manifest's field table, the residual
risk and the k table. No server, no state, no key. It opens offline and keeps
working when this tool is gone.

**It contains patient data, and it is the only output of `commissura` that
does.** The "before" half of each comparison is an unredacted clinical report.
That is the point of the page and it makes the file something that must stay
inside your organisation, so:

- **it is never written inside the dataset directory, and the command refuses
  rather than warning.** A file there would be digested into the manifest's own
  integrity list and released with the dataset. `--report ./dataset/report.html`
  is the obvious thing to type and is exactly the mistake;
- the page says what it holds in its first screenful;
- you name the file, because there is no safe default place for something that
  must not be filed with the dataset;
- it is opt-in, and stays opt-in.

```
  html report            /home/you/review.html
                         CONTAINS PATIENT DATA - do not release it
```

#### The field table is observed, not declared

The manifest's per-modality table is derived from the run. Every field the input
actually carried is listed with the number of files that held it, so a field
nobody anticipated is accounted for rather than going unmentioned:

```json
{ "field": "00100030", "name": "PatientBirthDate",
  "disposition": "removed", "files_present": 27 },
{ "field": "0020000D", "name": "StudyInstanceUID",
  "disposition": "replaced", "files_present": 27,
  "note": "as an HMAC-derived UID under the 2.25 arc" },
{ "field": "00290010", "disposition": "removed", "files_present": 4 }
```

That last row is a private vendor tag, present in four of twenty-seven files
because a defect put it there. Nothing declares it; it is in the table because
it was in the data, and an odd DICOM group number means its meaning belongs to
the vendor and is in no dictionary.

This works because **the build carries a whitelist, not a blacklist**: the lab
branch writes nine columns and the imaging branch seven keys, and everything
else is dropped by never being copied. So removal needs no list — only the
carried fields are declared, and whether each one passes through the
pseudonymiser, which is a fact about the code rather than about the data. A
`replaced` value is still relinkable by whoever holds the key; a `kept` value is
the original.

A label this tool does not recognise is reported as a class rather than
quoted, because a header label from somebody else's template is written beside
the value it labels and is a line of the input:

```json
{ "field": "other labelled lines", "disposition": "removed", "files_present": 12 }
```

That row is how you find out your template carries fields this tool never saw —
the same signal as reports landing in `records_dropped`, in the table rather
than in a count. **It is the one fragment on this page that is not a real
capture**, because the walkthrough's own corpus uses labels this tool
recognises, so no such row appears in its manifest.

A report's prose body is not a field, so the reports modality carries a second
table beside the first, with the same three-way vocabulary:

```
category           disposition   documents   occurrences   marker
institution        removed              19           170   [INSTITUTION]
date               replaced             19            34   [day_offset:N]
date_of_birth      removed              19            19   [BIRTH-DATE]
provider_name      removed              14            29   [PROVIDER]
contact            removed               6            12   [CONTACT]
age                replaced              0             0
```

Both counts are there because for prose they answer different questions:
`documents` is coverage, `occurrences` is how many identifiers the method
actually found. `date_of_birth` sits with the removed and not with the dates on
purpose — an offset from the subject's own baseline would state the birth date
exactly in a dataset that also carries the baseline.

`contact` covers 6 of the 19 documents, because a discharge letter carries a
follow-up contact and a radiology report has no reason to. That partial coverage
is the point of counting documents separately from occurrences.

The row at zero is a rule that did not fire in this corpus — twenty-five people
produced nobody above the age ceiling — reported rather than omitted, because an
omitted row reads as "no such rule". The first run of this table had `contact`
at zero too, and that *was* a finding: the generator never wrote an email or a
telephone number into a report body, so the contact rule and the ordering fix
behind it were exercised by one unit test and by no corpus the tool produced.
A generated discharge letter now carries one, in prose rather than in a labelled
field, so only the patterns can find it.

#### Linkage is accountable

A subject exists only if a laboratory message established it, because the HL7
message carries the national identifier and a DICOM header does not. Every
record that cannot be attached produces an issue naming the file and the reason,
and the count goes into the manifest — it is the number to look at before
trusting a dataset.

**Where that identifier sits is not one answer.** The reader looks in the PID-3
identifier list first, for a repetition whose type code is `NNITA` or `NI`, and
falls back to PID-19. PID-19 was deprecated in HL7 v2.3.1 and an Italian
installation carries the codice fiscale in PID-3 with a type code — but
deprecated is not switched off, and plenty of interfaces still send it there. A
generated corpus contains both forms, one site per interface, because a fallback
no corpus exercises is a fallback nobody has tested.

The type code is worth a sentence of its own: **HL7 v2 table 0203 has no
concrete code for Italy.** It documents a pattern, `NNxxx`, "National Person
Identifier where the xxx is the ISO table 3166 3-character (alphabetic) country
code", so `NNITA` is that pattern instantiated rather than a listed concept.
`NI`, "National unique individual identifier", is listed, and some systems use
it instead. The reader accepts both; the writer emits `NNITA`.

Record numbers are compared with leading zeros stripped, which recovers the
`imaging.mrn_format_drift` defect: at `--defect-rate 1.0` across twenty
subjects, no imaging study is lost. That defect is the one that silently halves
a cohort when somebody joins on the raw identifier.

#### And over the laboratory values

```
  laboratory values      60 subject(s)
  analyte-value combos   478
  below k=5              469  (98.1% of combinations)
  minimum k              1
```

The same question as age and sex, asked of a column nobody calls identifying. A
haemoglobin of 13.2 that nobody else in the cohort shares is a handle on
whoever has it, for anyone who knows that one value — and a clinician, a
relative or a previous employer may well know it.

Counted **per subject, not per row.** The same person measured three times at
the same value is one person; counting rows would report a patient with frequent
bloods as *less* identifiable than one with a single test, which is backwards.

**98.1% of 478 combinations on sixty subjects, and tripling the cohort moved
that figure by two points.** That is the real finding and it is not a defect in
the dataset: a measured value is a near-unique quantity, not a category, so
almost every analyte-and-value pair belongs to one person. **Full k-anonymity
over continuous multivariate clinical data is not reachable, and no cohort size
gets you there.**

That is worth saying plainly because it explains the shape of the whole
regulation. The EHDS does not protect secondary use by requiring anonymisation —
it protects it with **data permits and secure processing environments**, because
for data like this anonymisation is not on the table. This report is a
measurement handed to whoever makes that judgement, and it is never a
certificate of anonymity.

**It reports and does not correct**, which is a decision rather than an
omission. Every remedy damages exactly what the data is for:

| Remedy | Why not here |
| --- | --- |
| Suppressing rare rows | The unusual value is both the risk and the reason somebody wants the dataset |
| Top and bottom coding | Removes the extremes, which is where the clinically interesting cases live |
| Rounding into bands | Same, more quietly: a creatinine banded to the nearest whole number is a different measurement |
| Adding noise | Worse in a clinical setting than most — an analyst who cannot say how far wrong their numbers are cannot reason about them at all |

Which of those is acceptable depends on the permit, the recipient and the
release arrangement, and only the data holder knows those. So `commissura`
measures, and the choice stays with the person who has to defend it.

The listing is capped at fifty combinations while the count stays exact: a
complete list would be the dataset again with its rarest values highlighted,
which is a worse artefact than the dataset, written into a file that travels.

### `commissura verify`

```bash
commissura verify ./dataset --key-file ./commissura.key
```

```
  files checked          52
  altered                0
  missing                0
  added                  0
  manifest               authentic

  INTACT: every recorded file matches its digest.
```

The manifest says what was done to the data. On its own it does not say the data
has not changed since — anybody can edit a value in a lab table or paste a name
back into a report, and the manifest goes on reading as though it were still
true. `build` records a SHA-256 per file it produced; this recomputes them and
reports what is altered, missing or added. It is the mirror of the check
`generate` already runs on its own output, where the recorded PHI offsets are
re-read from disk rather than trusted.

**What it proves depends on whether you have the key.** The digest list lives in
the manifest, so whoever can change a report can change the list beside it. The
digests catch the things that happen by accident: a TSV opened in a spreadsheet
and saved back, an incomplete copy, a stray export dropped into the tree. The
manifest also carries an HMAC over its own content, keyed by the secret, and
`--key-file` checks it — that is the part that catches a deliberate edit:

```
  manifest               DOES NOT MATCH ITS OWN TAG

  TAMPERED: the manifest does not match its own authentication tag, so its
  contents were edited after the build.
```

Zero files differing *and* a failed tag is the signature of somebody adjusting
the manifest to cover their tracks, which is why the two are reported apart.
Without `--key-file` the output says "not authenticated" rather than anything
reassuring: unchecked and checked-and-fine must never read the same way.

### `commissura measure`

```bash
commissura measure ./raw ./dataset
```

```
  category          planted  measured  removed  survived
  accession             314       314      314         0
  address               525       525      525         0
  age                   132        84       84         0  (kept by design)
  contact               253       253      253         0
  date                  533       533      533         0
  device_id             168       168      168         0
  institution           316       241      241         0
  national_id           143       143      143         0
  patient_id            259       259      259         0
  person_name           377       373      373         0
  provider_name         440       434      434         0
  uid                   168       168      168         0

  recall                 100.00%  of 3411
  survived               0
  too short to measure   58  (under 4 characters)
  declared by the holder 75  (publisher, HDAB, title)
  records not included   3  (their identifiers are absent because the record is,
                                 not because redaction removed them)
  dataset files searched 217
```

**100% of 3,411 measurable planted identifiers removed**, on the corpus the
walkthrough above builds. That number is the point of this project. "Rules
first, measurement always" is easy to write and the measurement half was a
promise until this command existed: the generator had been recording every
identifier it planted, with the file and character offsets, and nothing had
ever compared that record to the output.

The ground truth is the unusual part. Real corpora are annotated by hand,
partially, expensively, and the annotation is itself uncertain. Here it is a
by-product of writing the text, so it is complete by construction — and a
measurement is only ever as good as what it is measured against.

**Three exclusions, each visible in the output rather than folded into the
number.** Spans under four characters are not counted either way: a two-letter
fragment of a surname matches inside "de-identification", so calling it a leak
invents one and calling it removed invents a success. Ages are kept on purpose
and reported apart. And strings the holder typed on the command line — the
publisher's name, the HDAB — are excluded, because a hospital publishing its
own data names itself in the description, and that name is also written across
every report in the corpus; it is in the output by the holder's decision, not
because redaction failed.

**A fourth number that is a caveat and not an exclusion.** `records not
included` counts identifiers in records the dataset left out — here the
thirteen reports with no readable date. Their identifiers are absent because
the record is absent, which is no evidence that redaction works: in the
degenerate case a build that dropped everything would score a perfect recall
for producing nothing. It is reported beside the figure rather than subtracted
from it, because attributing it span by span would need the file paths, and
those are deliberately not in the manifest.

**And one limit no exclusion fixes.** This asks whether the *exact* planted
string survived. Half an institution name surviving is not a miss here and
never will be. That question is answered by the scrubber's residual-risk list,
which works the other way round — it looks at the output for anything shaped
like an identifier, without knowing what was planted. The two fail differently
on purpose and a reader needs both.

#### On a corpus with injected defects, it is not 100%, and that is the finding

```bash
commissura generate --subjects 5 --seed 23 --defect-rate 0.6 --out ./rough
```

Recall drops to **98.45%**, and every survivor is a clinician's name in a
report. The cause is two defects meeting: `reports.missing_author` removes the
signature block, which is the only structured field naming that clinician, and
`reports.identifier_in_prose` leaves them named mid-sentence in the body.
Targeted redaction cannot reach a name nothing declared.

That is the method's documented limit with a number attached to it rather than
a caveat in prose. Closing it would mean named entity recognition, which this
project rejects on the evidence that general-purpose tools miss over half of
clinical PHI. So the test suite pins the clean corpus at 100%, pins the
defective one above 95%, **and pins that every survivor is a person's name in a
report** — because a bound alone would stay green while the failure changed
character into something that is a defect rather than a limit.

#### What it found on its first run

Two leaks, neither visible by reading the code:

- **The manifest recorded the corpus's absolute path**, which on any ordinary
  machine contains the operator's account name, inside the one document written
  to be sent to an access body. A generated clinician who happened to be called
  JONATHAN is what made it visible. It now records the directory's name.
- **The residual-risk list quoted the tokens it was warning about.** A patient's
  surname appeared in `.deident/manifest.json` of a dataset from which every
  other trace of it had been removed — the document saying "I could not remove
  these" was handing them over. It now reports a count and a length range, and
  the file path tells a reviewer where to look.

Two more came later, from an audit that went looking for the same pattern a
fourth time — *for every field of the manifest, can it carry something derived
from the input?* It could, twice. A linkage issue and a dropped record each
carried a `detail` sentence built from the file that failed, so an unlinked
report put a codice fiscale in the document, and an unreadable file put a path
and an exception message there. Both are now counted by reason, and `build`
prints the paths to the terminal, which does not travel. The shape had been
wrong since linkage issues were first recorded and never fired, because every
corpus tested had none: an empty list hid an unsafe shape.

A third, found while measuring a smaller corpus: a site that sent laboratory
messages and wrote reports but produced no imaging study had its street address
printed in every report header and never redacted, because imaging metadata was
the only place addresses were learned from. Its *name* was removed, which is
what made it hard to see — the header read `[INSTITUTION]` above an intact
street and city. Addresses are now also read from the line under an institution
the structured exports already named.

### `commissura whois`

```bash
commissura whois RSSMRA80A01X000Z --key-file ./commissura.key
```

```
  subject label                   8ac2e8cedbde
  directory                       sub-8ac2e8cedbde
  identifier, normalised          RSSMRA80A01X000Z
  key fingerprint                 bb0be87afcf8eb23
  de-identification rule version  1.1.0
```

**The identifier is validated and normalised first**, with exactly the rules
`build` uses, through the same function. That matters more than it looks: the
label this command prints has to be the label the dataset carries, or the search
it exists for comes back empty for the wrong reason. Case, surrounding and
internal whitespace, and compatibility-encoded digits all normalise. A value
that cannot key a subject — a placeholder, a wrong check character, the wrong
shape — is refused with exit code 2 and the diagnosis, rather than given a label
that corresponds to nobody.

**This is what an EHDS opt-out needs in a dataset you have already released.**
Somebody exercises their right to object. You know exactly who they are; the
datasets already in somebody else's hands contain no name, no codice fiscale and
no record number. The subject label is the only handle that connects the two,
and this derives it. For the datasets you have *not* built yet, give the
identifier to [`build --exclude-subjects`](#acting-on-an-opt-out) instead and
the person never appears at all.

It reads nothing. The label comes from the identifier and the key, so the
answer is the same whether or not that person is in any dataset — which is
deliberate, because a command that *looked it up* would be answering "is this
person in this dataset?", a different and far more dangerous question. Check
the key fingerprint against the one in a dataset's manifest before trusting a
label against it.

Pipe the identifier instead of typing it when you would rather it stayed out of
your shell history. It is patient data, and the argument for keeping the key
off the command line applies to it too:

```bash
echo RSSMRA80A01X000Z | commissura whois --key-file ./commissura.key
```

**There is no command that goes the other way, and there will not be.** The
label is an HMAC truncated to twelve hex characters: no inverse exists to
implement, and the truncation means "the identifier for this label" is not even
a well-defined question. The only way to fake one is to enumerate the
identifier space and build a lookup table — which is precisely the attack this
design was chosen to resist, and a codice fiscale is derivable from a name, a
birth date, a birthplace and a sex, so that space is enumerable for anyone
somebody is actually interested in. A test asserts no such command exists.

### `commissura risk`

```bash
commissura risk ./dataset
```

```
  participants           10
  quasi-identifiers      age, sex
  minimum k              1
  below k=5              10 combination(s)
    k=1  age=22, sex=M
    k=1  age=36, sex=F
```

A dataset with no name in it can still identify somebody. If one participant is
the only 94-year-old woman in the cohort, that row is unique on attributes
nobody thinks of as identifiers.

`build` writes the report automatically, which is what `validate` looks for.
Note the honest result above: on ten participants with exact ages, minimum k is
1. Ten people cannot reach k=5 on age and sex together — a property of small
cohorts, not a defect, and the command reports the number rather than a verdict.

**The report also names the channels k cannot score, and that is the part worth
reading.** `risk_report.json` carries a `quasi_identifier_channels` list naming
every route out of this dataset that a quasi-identifier could take: the
participant demographics, the laboratory measurement values, the imaging
acquisition metadata, and — the one that matters most — the **event interval
sequence**.

Intervals between a subject's events are exact. One true calendar date for that
subject, from any other source, dates every other event in their record. That is
the most likely route from a dataset built here back to a person, and
k-anonymity cannot put a number on it: k counts people sharing a combination of
attribute values, and a sequence of day offsets is not an attribute with a value
domain.

Which is exactly why it has to be *listed*. Dropping a channel for being
unscoreable is how the strongest one in the dataset becomes the one your report
does not mention. Each entry says whether a k was computed, and when none was,
why not and what mitigating it would cost. TEHDAS2 D7.2 makes the hand-over an
explicit step for whoever pseudonymises, and gives hospital visit dates as its
own worked example of the kind this file has to carry.

**Integrity is not completeness.** `verify` answers one question: do the files
match the digests the manifest records? A dataset still holding a record you
withdrew from the corpus verifies perfectly, because its bytes have not changed
since the manifest was written. The command says so in its own output. Four
different claims, and only the first two are things `verify` can speak to:

| Claim | Who establishes it |
| --- | --- |
| Integrity — the files are unchanged | `verify`, from the digests |
| Authenticity — the manifest is unedited | `verify --key-file`, from the HMAC |
| Completeness — the dataset holds what it should | Rebuilding from the current corpus |
| Correctness — it holds the right things | You, and the linkage issues |

**k-anonymity is a measurement, not a certificate, and this tool pseudonymises
rather than anonymises.** The distinction carries the whole legal weight:
pseudonymised data is still personal data under the GDPR, anonymised data is not.
The Commission's EHDS FAQ treats pseudonymisation and anonymisation as
alternatives and puts ultimate responsibility for either on the Health Data
Access Body, so a dataset built here is an input to that judgement and never the
judgement itself.

Not an Article 78 quality and utility label: those criteria are not published
yet.

#### Conformance is checked against the profile's own shapes

Not against this project's reading of the specification. `pyshacl` loads
HealthDCAT-AP Release 8's SHACL shapes, its `range.ttl`, and the DCAT-AP 3.0.0
shapes *and* class ranges, then judges the emitted description.

```bash
pytest tests/test_shacl_conformance.py
```

**The shapes are in this repository, under `third_party/`.** Nothing to
download, nothing to configure: clone, install the dev extra, and the claim is
checked — on your machine and on every push.

**Conformant is not the same as true, and that gap had three things in it.**
SHACL judges structure: `"integer"` is a valid CSVW datatype whatever the
column holds, and `"synthetic"` is a well-formed keyword for real patient data.
A pass over every property the description emits found that `reference_low` and
`reference_high` were declared `integer` while the column holds `0.30` and
`17.0`; that the keywords asserted `imaging` for a dataset with no imaging
study; and that `--dataset-type TEST_DATA` left `synthetic` in the keywords of
the same record, with no flag to change it. The keywords are derived from what
the build produced now — `clinical`, plus a term per modality actually present,
plus `synthetic` only when the declared dataset type says so — and
`--keyword` replaces the set:

```bash
commissura build ./raw --out ./dataset     --keyword oncology --keyword "outcome research"     --identifier "urn:irccs-marebianco:lab-2029-01"
```

**`--identifier` exists because the default collides.** `dct:identifier`
defaults to `urn:commissura:<output directory name>`, so two holders who both
run `build --out ./dataset` submit the same identifier to the same catalogue.
Nothing here can invent a globally unique name, so set it if your record will
sit beside somebody else's.

One limit of the profile rather than of this tool, recorded because a holder
hits it: `dct:type` is mandatory and its authority list has twenty-two
concepts, **none of which means "personal electronic health data"**. The
closest honest values for real clinical material are `TEST_DATA` or a
statistical type, and neither is right. `SYNTHETIC_DATA` is correct for this
project's own output and is the default for that reason.

It used to work the other way, and that was the problem. The shapes were
fetched on demand into a gitignored directory and the test *skipped* when they
were absent, so the headline claim of this project was verified wherever one
person had run four `curl` commands and nowhere else. CI showed a green tick for
a check it never performed. A skip is a silent failure, and it hid a real one
once already: the download commands printed here were broken for weeks — they
used `curl -O` against an endpoint whose path ends in `/raw`, so every file
landed as `raw` and each overwrote the last — and following them produced a tidy
skip rather than an error.

Two works are redistributed, both under CC BY 4.0, which permits it with
attribution: **HealthDCAT-AP Release 8** (European Commission, DG SANTE /
HealthDataEU) and **DCAT-AP 3.0.0** (SEMIC), the second because the first
imports it. [NOTICE](https://github.com/jonathanmanca/commissura/blob/main/NOTICE) carries the attribution and
`third_party/PROVENANCE.json` carries the bytes — per file, the URL it came
from, the date, and a SHA-256 that `tests/test_vendored_shapes.py` checks on
every run. The files are unmodified; the one defect in the published shapes is
repaired on the parsed graph at load time and never in the file.

To refresh them, re-download from the `url` recorded for each file and update
its `sha256`:

```bash
uv run python -c "import json;[print(f['path'], f['url']) for w in json.load(open('third_party/PROVENANCE.json'))['works'] for f in w['files']]"
```

That is deliberately a manual step. **Pinning a copy trades one kind of
awareness for another**: the repository now always has the shapes, and in
exchange it no longer finds out on its own when upstream changes them.

**The first run found eleven distinct violations** that reading the cardinality
table had not revealed — six of them came from the imported DCAT-AP 3.0.0 shapes
and from `range.ttl`, which the health shapes do not contain. Among them: every
distribution needs a `dcat:accessURL`; both the HDAB and the publisher need a
`cv:contactPoint`; `dct:type` must be an IRI from an authority list and not a
string; record counts must be `xsd:nonNegativeInteger` and not the `xsd:integer`
a bare JSON number becomes; and a `healthCategory` reference must be a typed
`skos:Concept` carrying its label.

**The second round found six more**, and finding them needed a defect in the
profile to be worked around first. HealthDCAT-AP's `range.ttl` says in its own
comment that it imports DCAT-AP's class ranges "to ensure clear distinction
between reused and extended constraints". It does not: it declares itself as the
DCAT-AP range IRI and then `owl:imports` that same IRI, so the import is a
self-loop and brings in nothing. **84 class range constraints were therefore
never being checked.** Loading DCAT-AP's `range.ttl` by hand turned up six
failures, all the same shape of mistake: `sh:class` is satisfied by an
`rdf:type` triple *in the data graph*, and a validator does not dereference an
authority list to find one. So `dct:accessRights`, `dct:format`, `dct:type` and
`dcatap:applicableLegislation` all needed to carry their class inline, and
`dcat:contactPoint` needed to be a `vcard:Kind`.

That last one is worth keeping straight: DCAT-AP constrains the dataset's
`dcat:contactPoint` to `vcard:Kind`, while the HealthDCAT-AP shapes constrain an
agent's `cv:contactPoint` to `cv:ContactPoint`. Two profiles, two contact
models. Each is used where its own shapes ask for it; picking one and using it
everywhere is the tempting move and fails half the shapes.

Three findings are about the profiles rather than about this project. **Release 8's
published shapes are not valid SHACL**: an `sh:or` sits inside the `sh:property`
list with no `sh:path`, which no property shape may lack, and a strict engine
refuses the whole file. The test repairs it on the parsed graph — not by editing
the download — and a second test fails once upstream fixes it, so the workaround
cannot outlive the defect. The self-import above is pinned the same way.

And **five constraints in the DCAT-AP 3.0.0 shapes are inert**: they use
`sh:shape`, which belonged to a SHACL draft and is not in the standard, where
the parameter is `sh:node`. `CatalogRecord_Shape` uses both, two lines apart,
for the same inner shape. A conformant engine silently ignores the `sh:shape`
ones, so the date-type checks DCAT-AP intends on `dct:modified`,
`dcat:startDate` and `dcat:endDate` are not enforced by anything. Nothing here
depends on them; it is recorded because "conformant" means less than it looks in
that corner.

And **one worked example points at a namespace that is not the vocabulary's.**
The example for `dpv:hasPersonalData` declares
`@prefix dpvpd: <https://w3id.org/dpv/dpv-pd#>`, while DPV's Personal Data
extension states that the namespace for its terms is
`https://w3id.org/dpv/pd#` — and `dpv-pd` appears nowhere in that vocabulary as
an alias. What makes it hard to catch is that `w3id.org` redirects both
document URLs to the same published page, so following the link from the
example shows a real specification and confirms nothing about the term IRIs,
which are compared as strings.

So the description names `pd:HealthRecord`, typed as both `dpv:PersonalData`
and `dpv:SpecialCategoryPersonalData` because DPV's own file declares it an
instance of each, and because a validator holding none of DPV's axioms needs
the triples in the document. The near miss is `pd:Health`; both are special
category, so the choice changes what the description says rather than what it
claims.

**There is no property for a trade-secret flag**, which is worth stating
because EHDS Article 60(3) has a holder notify intellectual property or trade
secrets when submitting a dataset description. The word "secret" appears
nowhere in the Release 8 specification, and "intellectual property" only in the
definition of `dct:rights` — which DCAT-AP 3.0.0 puts on a catalogue and a
distribution, not on a dataset. The notification is out of band.

### Synthetic by construction

"Probably not real" is not good enough for clinical identifiers, so each one is
placed where no authority assigns:

| Identifier | Why it cannot be real |
| --- | --- |
| Codice fiscale | Place-of-birth code uses an `X` prefix; municipalities are assigned `A`–`M` and foreign states `Z`. The checksum is still valid, so the values exercise a real validator. |
| Telephone | Subscriber part starts with `0`, which is never assignable after an Italian area code. |
| Email | `.invalid` is reserved by RFC 2606 and can never be registered. |
| DICOM UID | The `2.25` arc holds UUIDs as integers, needs no registration, and collides with nobody. The integer really is a UUID: the digest's first sixteen bytes carry RFC 9562 version 8, the form defined for one built from application-chosen bits, so a consumer decoding a `2.25` OID gets a valid answer rather than a plausible one. |
| Institutions | Invented names at invented addresses, every one marked `SINTETIC`. |

## Development

[![CI](https://github.com/jonathanmanca/commissura/actions/workflows/ci.yml/badge.svg)](https://github.com/jonathanmanca/commissura/actions/workflows/ci.yml)
[![Upstream dependencies](https://github.com/jonathanmanca/commissura/actions/workflows/upstream.yml/badge.svg)](https://github.com/jonathanmanca/commissura/actions/workflows/upstream.yml)

Every push and pull request to `main` runs `ruff check`, `ruff format --check`,
`mypy` and `pytest` on Python 3.11 to 3.14 on Ubuntu, and on 3.14 on Windows,
**installing from the lockfile**. It then builds the same dataset from the same
seed and the same key on Ubuntu and on Windows and **compares the per-file
digests**, because for a tool whose output is meant to be verified later,
reproducibility is a property worth proving rather than assuming.

Three things have to match for that comparison to mean anything, and all three
are pinned in the workflow: the seed, the key, and the *name* of the output
directory — `dct:identifier` is derived from it, so building into `ds_a` and
`ds_b` legitimately produces two different documents. That was found by running
the comparison locally before writing the job, which is the only reason it is
not the first thing the job reported.

The two badges mean different things on purpose. **CI** is the gate: it installs
the locked dependency set, so a red tick means the commit in front of it broke
something and not that the world moved. **Upstream dependencies** is a weekly
canary that ignores the lock and resolves freely on 3.11 and 3.14; a red tick
there means a newly published version of `typer`, `pydantic`, `ruff`, `mypy` or
`pyshacl` no longer works with this code. That is worth knowing and worth
blocking nobody's merge, which is why it is a separate workflow: a failure in it
would otherwise turn the CI badge red and the badge would stop meaning "this
code is good".

```bash
uv sync --locked --extra dev
```

```bash
pytest && ruff check . && ruff format --check . && mypy
```

`uv.lock` is committed and pins all 40 packages, so two people installing a
month apart get the same dependency set. `--locked` fails rather than silently
re-resolving when `pyproject.toml` and the lock disagree, which is what you want
in a checkout and in CI: a lock that quietly updates itself is not a lock. After
changing a dependency, refresh it with `uv lock` and commit the result.

This is not theoretical. The first `uv sync --locked` in this repository replaced
the already-installed `typer` 0.28.0 with 0.29.0 — two installs of the same
unchanged project, days apart, resolving differently, which is exactly the thing
a lockfile exists to stop happening silently.

`pytest` measures branch coverage on every run and fails below 99%. The
threshold is enforced in configuration rather than offered as a flag, because a
threshold that applies only when somebody remembers to ask for it is not one.
To skip it while iterating on a single test:

```bash
pytest --no-cov tests/test_hl7.py
```

It is a regression floor, not a target. Coverage says a line ran, not that it
was checked, so the suite is written to pin the decisions that are easy to undo
by accident: that `--defect-rate 0` reports no defects, that a clean corpus is
still hard to de-identify, that institution names carry a synthetic marker with
no exceptions, that HL7 files contain no line feed, and that `verify_corpus`
actually fails when a file is altered.

The floor is Python 3.11, and `mypy` is configured against it, so a standard
library call added in a later version is caught even when the tests run on a
newer interpreter — this is how `Path.read_text(newline=...)`, which is 3.13 and
later, was caught before it shipped. To exercise the floor itself:

```bash
uv run --python 3.11 pytest
```

## Problems and questions

**Report a problem as a
[GitHub issue](https://github.com/jonathanmanca/commissura/issues).** To reach
the author some other way, the package also declares the profile
[linkedin.com/in/jonathan-manca](https://www.linkedin.com/in/jonathan-manca/).
What changed between releases is in [CHANGELOG.md](https://github.com/jonathanmanca/commissura/blob/main/CHANGELOG.md).

**Do not send clinical material, and do not send a key.** That request is not
politeness about mailbox sizes: a bug report about a de-identification tool is
exactly the place somebody pastes the message that reproduces it, and a message
that reproduces a de-identification bug is by definition one this tool failed to
de-identify.

Nearly everything reproduces on synthetic data, because the generator ships in
the same package and its corpora are deterministic. A seed, a subject count and
a defect rate are usually the whole report:

```bash
commissura generate --out ./raw --subjects 25 --seed 42 --defect-rate 0.2
```

What helps, in order: the command you ran, the output of `commissura --version`,
your platform, and the `--json` output of whatever went wrong.
`.deident/manifest.json` and `.deident/risk_report.json` are safe to attach
whatever corpus they came from — they are built to carry counts and never
values, and a test asserts that no planted identifier reaches them.

**Never the `--report` page.** Its left-hand column is the input before
redaction, which is the one artefact this tool produces that must not leave the
machine that built it.

## Licence

Apache-2.0. See [LICENSE](https://github.com/jonathanmanca/commissura/blob/main/LICENSE) and [NOTICE](https://github.com/jonathanmanca/commissura/blob/main/NOTICE).
