Your medical history, owned by you.

Pulse is a lifelong electronic health record. Providers add to it. Clinicians read it only with the patient's consent. Every access is written to a log the patient can read, and nobody can rewrite.

55 endpoints, each declaring the permission it needs. 18 architecture decisions, written down. 4 languages. Zero real patients.

Aishani's timeline synthetic patient
  1. Lab report HbA1c 7.9 % High, above 5.7
  2. Prescription Metformin 500 mg, twice daily
  3. Diagnosis Type 2 diabetes mellitus SNOMED CT 44054006
Dr. Rao viewed 3 entries inside an active consent. Recorded in the audit log.
See the actual app in light and dark

Captured from the local synthetic demo. The story uses the same burgundy theme and Noto typeface.

Light interface

The real Pulse public entry page in its light burgundy theme

Dark interface

The real Pulse public entry page in its dark burgundy theme

Chapter 1

Your history lives in pieces, and nobody can see them all

A person's medical history is not in one place. Every place that treated them kept its own part, and the person is the only thing connecting the parts.

Each place keeps a piece

A hospital holds the admission and the surgery. A clinic holds three years of follow-up notes. A lab holds its own reports, readable in its own portal. A paper file sits in a drawer at home. A photograph of a prescription sits somewhere in a phone's gallery.

None of these talk to each other. Each is complete for the people who made it and blind to the rest.

The patient is the integration layer

When someone new needs the history, the patient reassembles it from memory and from whatever they remembered to bring. Whatever gets forgotten or repeated is the cost of that, and the patient is the one who pays it.

And they cannot see who looked

Anyone able to open a fragment can read it. Nothing is built to tell the patient that it happened. A person can be unable to find their own report and still have no way to know who else has read it.

One synthetic patient's history, scattered then joined Eight cards, each marked with where it is kept: hospital, clinic, lab, a paper file and a phone photo. Scattered on the left at first, they slide to the right and line up on a single vertical timeline. Diagnosis Hospital Prescription Paper file Lab report Lab Clinical note Clinic Lab report Phone photo Procedure Hospital Prescription Clinic Lab report Lab
Today: eight pieces, five places. Illustration of one synthetic patient. With Pulse: the same eight pieces on one timeline the patient owns.

Share it for care. Keep it private by default.

Care needs the history to travel

A clinician deciding on a prescription needs the diagnoses, the other medicines and the last lab result in front of them, now, not after a phone call and a courier.

Privacy needs it to stay put

A medical history says things a person may tell nobody else. If it is open to anyone who can log in, the patient has no way to hold it back and no way to know who read it.

Pulse does not pick a side. It moves the decision to the patient: sharing is something the patient grants to a named person, for a stated scope and time, and every use of it leaves a record they can read. The next chapter states that as four rules. Read the promise.

Chapter 2

Four rules, each enforced by something that cannot be skipped

Pulse is one sentence in four clauses. None of them is a policy document. Each is held in place by a table shape, a query, a test or a database grant.

  1. Patients own their history.
  2. Providers contribute to it.
  3. Clinicians read it only with the patient's consent.
  4. Every access is recorded.

Patients own their history

The Patient row is the root of everything clinical. Medical Entries, consents and audit events all point at patient.id. There is no separate "patient record" entity that could drift from the person.

patient.user_id is nullable on purpose. A Patient can exist before the person has an account, so a Provider can file for someone who has never registered. The demo data has 37 of its 125 patients in that state. The screen that creates an unclaimed Patient, and the step where the person later claims it, are not built; filing for an existing Patient ID is.

ADR-0002 Domain model

Providers contribute to it

Provider Staff are the only role that holds RECORDS_WRITE. They file any of the 5 kinds of Medical Entry and attach documents. Nobody edits or deletes an entry afterwards: a correction inserts a new one and stamps the original as superseded, so the history shows what was believed and when.

Contributing is not reading. Staff list back only the entries their own provider authored, and the Patient can read all of them.

Who holds which permission ADR-0001

Clinicians read it only with the patient's consent

A role alone opens nothing. A Clinician reads a Patient's entries through a consent that names that Clinician, limits the entry types and an optional date window, and lasts until the Patient revokes it. Consent goes to a person, never to a hospital, so agreeing to it can mean something.

The check is part of the SQL, in one query builder every read goes through. A refused read returns 404, so a refusal does not reveal that the person is a patient at all.

There is one deliberate exception. A Clinician can request 60-minute emergency access with a written reason. It opens only the Patient’s emergency card, never their records, and the Patient is notified.

The consent engine, try it ADR-0006 ADR-0010

Every access is recorded

The service layer writes an Audit Event explicitly, once per access: a 50-entry timeline is one ENTRY_VIEWED, and a refused read writes ACCESS_DENIED. No clinical value ever goes into an event, so the log cannot become a second copy of the record.

The application's database role holds only INSERT and SELECT on audit_event. The database refuses UPDATE and DELETE, even from our own code. The Patient reads their own log. An administrator audit viewer is not built.

ADR-0008 Architecture

What Pulse refuses to do

No administrator reads clinical data
The Administrator role holds no RECORDS_READ, and there is no override. Merging duplicate patients is decided from name, birth date, phone, address and entry counts, never from the entries. ADR-0007
No consent to an organisation
Consent is granted to one named Clinician. Agreeing that a hospital may read a history means agreeing to an unbounded, changing set of people. A Clinician who changes jobs keeps their consents. ADR-0010
No real patient data, ever
Every record is synthetic: Synthea v4.0.0 output plus an Indian identity overlay, with generated names and phone numbers in a sentinel range. This is an academic project and never touches a real person. ADR-0015

Chapter 3

Four roles, and what each one cannot do

Who a person is decides which of eighteen permissions they hold. The list is closed and the mapping lives in one short file, so the answer to 'can a Clinician do this' is a lookup, not an investigation.

Roles are PATIENT, PROVIDER_STAFF, CLINICIAN and ADMINISTRATOR. Permission is an enum of 18 members, and ROLE_PERMISSIONS is a plain table from role to a frozen set of them, resolved without a database or a request. It is all in backend/app/core/authz.py. Pick a role to see its column.

Patient

Holds 14 of 18 permissions

Can. Owns the record. Reads their own timeline, grants and revokes consent, keeps an emergency card with a QR, sees every access in their audit log, reads analytics and notifications, and asks plain-language questions of their own record.

Cannot, or only within limits. Cannot file or edit clinical entries.

Which role holds which permission. The chosen role's column is highlighted.
Permission PatientStaffClinicianAdmin
Identity and profile
Read own profile PATIENT_PROFILE_READ_SELF
Change own interface language PATIENT_PROFILE_UPDATE_SELF
Change own credentials USER_CREDENTIALS_CHANGE
See a provider's public name and city PROVIDER_READ
Clinical records
Read Medical Entries (rows filtered per request) RECORDS_READ
File entries and attach documents RECORDS_WRITE
Consent and emergency access
Review own consents CONSENT_READ_SELF
Grant and revoke own consents CONSENT_MANAGE_SELF
List patients whose consent names me CONSENT_READ_GRANTED
Request emergency-card access with a reason BREAK_GLASS_REQUEST
Edit own emergency card and QR EMERGENCY_CARD_MANAGE_SELF
View an emergency card by QR or break-glass EMERGENCY_CARD_VIEW
Audit and notifications
Read own audit log AUDIT_READ_SELF
Read own notifications NOTIFICATION_READ_SELF
Read notification preferences NOTIFICATION_PREFERENCES_READ_SELF
Mark read, change preferences NOTIFICATION_MANAGE_SELF
Data quality and administration
Read data-quality flags (identity only) ANALYTICS_DATA_QUALITY_READ
Review and merge duplicate patients ADMIN_DUPLICATE_REVIEW

A new endpoint cannot ship without saying who may call it

Holding RECORDS_READ answers whether a Clinician may read records at all. It never answers whether this Clinician may read this Patient's. That second question is the consent filter in the consent engine chapter. The permission table is the coarse first gate.

42 of the 55 endpoints declare either requires(PERMISSION) or an explicit public() marker. The other one, GET /api/v1/health, is a liveness probe named in an allowlist inside the test. The test walks every route's dependency tree and fails if one has neither, so the usual failure, an endpoint added late at night with no check at all, turns the build red instead of returning someone's records. A second test proves the check bites by running it on a router that is deliberately undeclared.

backend/tests/test_route_coverage.py, lines 52-64
Inspect the source excerpt
def _walk(dependant: Dependant) -> Iterator[object]:
    """Yield every `.call` in the dependency tree, depth-first."""
    for sub in dependant.dependencies:
        if sub.call is not None:
            yield sub.call
        yield from _walk(sub)


def _declares_marker(route: APIRoute) -> bool:
    return any(
        hasattr(call, PERMISSION_ATTR) or hasattr(call, PUBLIC_ATTR)
        for call in _walk(route.dependant)
    )

Chapter 4

A correction keeps the original

A clinical entry has two times: when the event happened and when Pulse recorded it. If Provider Staff corrects it, Pulse links a replacement instead of rewriting history.

A Patient starts with an account

Self-registration creates a Patient account. Pulse sends a verification email with a link that expires after 24 hours; after verification, the Patient signs in. Provider, staff and Administrator onboarding is not public signup.

Patient registration form on a phone
Verification email sent confirmation on a phone
Sign-in page with synthetic demo account buttons
Patient profile displaying a Patient ID that can be copied

After sign-in, the Patient profile shows a Patient ID. Provider Staff opens an existing Patient by that exact ID; general patient search is not available. An unclaimed Patient flow is not exposed in the UI.

Provider Staff files the event

Staff chooses a Medical Entry kind, adds its typed clinical fields and clinical date, and can attach a PDF, PNG or JPEG Medical Document. The system keeps the file bytes outside the database and stores metadata with the entry.

Provider Staff form for filing a typed clinical entry with a document option

The Patient reviews a chronological timeline

The Patient can narrow the timeline by entry type, text, date range or Provider, open an entry detail, and preview a supported attached document. The detail distinguishes event time from recorded time. Clinical content stays as recorded across the four interface locales. A whole-history export is not implemented.

Patient timeline on a phone with synthetic entries
Timeline with a type filter and other search controls applied
Patient Medical Entry detail with result and reference range

Navigation changes language; clinical text does not.

Patient timeline interface in Hindi with clinical content retained as recorded
Patient timeline interface in Tamil with clinical content retained as recorded
Patient timeline interface in Malayalam with clinical content retained as recorded
Patient timeline in the dark theme with synthetic entries

The Patient timeline sorts by clinical time. The record also retains its recorded time, so a report added later can still appear where the event belongs.

Correction is a Provider Staff action. The replacement is a new Medical Entry; the original receives a superseded_by_id link and remains in the correction chain. The current timeline omits superseded entries.

The distinction matters when a value was entered incorrectly: a visible correction can explain the change without making the first version disappear.

How entries and correction links are stored
Provider Staff entry detail with the correction action available
Patient view showing that an entry has been superseded

Original / retained

Initial lab result

Recorded on the timeline with its clinical date and source Provider.

Replacement / current

Corrected lab result

A second entry points back to the original. Only this version appears in the current timeline.

One current entry is shown. The correction chain is available from its detail.

backend/app/modules/records/service.py, lines 269-315
Inspect the source excerpt
async def supersede_entry(
    session: AsyncSession,
    actor: Actor,
    patient_id: UUID,
    original_id: UUID,
    payload: EntryCreate,
) -> EntryDetail:
    """Correction path (P2.7): insert a new Entry, stamp `superseded_by_id`
    on the original. Never an in-place update of clinical data. The route
    restricts this to Provider Staff (RECORDS_WRITE)."""
    if await users_service.get_patient(session, patient_id) is None:
        raise _not_found()
    await users_service.lock_patient_for_write(session, patient_id)
    original = await repository.get_entry(session, actor, original_id)
    if original is None or original.patient_id != patient_id:
        await _deny_access(session, actor, original_id)
    _validate_payload(payload)
    provider_id = await users_service.get_provider_for_staff(session, actor.user_id)
    if (
        actor.role is not Role.PROVIDER_STAFF
        or provider_id is None
        or (payload.source_provider_id is not None and payload.source_provider_id != provider_id)
    ):
        raise PulseError(
            ErrorCode.FORBIDDEN, "An associated provider is required.", http_status=403
        )
    payload = payload.model_copy(update={"source_provider_id": provider_id})
    replacement = await repository.supersede_entry(session, actor, patient_id, original_id, payload)
    if replacement is None:
        raise PulseError(
            ErrorCode.ENTRY_ALREADY_SUPERSEDED,
            "This entry has already been corrected.",
            http_status=409,
        )
    await audit_service.emit(
        session,
        actor=actor,
        action=AuditAction.ENTRY_CORRECTED,
        resource_type="medical_entry",
        resource_id=replacement.id,
        patient_id=patient_id,
        outcome=AuditOutcome.SUCCESS,
    )
    fresh = await repository.get_entry(session, actor, replacement.id)
    if fresh is None:  # pragma: no cover - just inserted
        raise _not_found()
    return projections.to_detail(fresh, supersedes_id=original_id, documents=[])

A Medical Document may be attached to an entry. Pulse stores and serves the file; it does not interpret it. See the records service.

Chapter 5

Consent names a person and a limit

A Clinician role alone reveals no Patient record. A Patient grants an individual Clinician access to selected entry types and a date window, for a set time.

Chapter 7

A record read leaves an audit event

Access transparency is part of the read path. A successful timeline request writes one event for the request, even when the page returns many Medical Entries.

The event records who acted, their role at the time, what resource they touched, when, and whether the request succeeded. The Patient sees a filtered projection: actor, action, time and entry type, without internal identifiers or clinical contents.

The app database role can insert and select audit rows. It has no update or delete grant, so immutability is enforced by PostgreSQL permissions.

A denied clinical read is also recorded server-side. Its event has no Patient link, so it does not appear in a Patient's audit view. This avoids exposing whether a denied identifier belongs to a Patient.

Metadata is kept to non-clinical fields by a typed shape and project rule. The break-glass justification is free text, so it still needs care not to include clinical details.

Why append-only is a database rule
Patient audit screen listing record views and consent events
A service emits an audit event inside the request transaction, then the database permits inserts and reads only records.serviceENTRY_VIEWED audit.service.emit()explicit event write audit_eventGRANT: SELECT, INSERTno UPDATE / no DELETE One event describes the access request, not one event per returned row.
backend/app/modules/records/service.py, lines 140-177
Inspect the source excerpt
)
    rows, next_cursor = await repository.list_timeline(
        session,
        actor,
        patient_id,
        entry_type=entry_type,
        cursor=cursor,
        limit=limit,
        from_date=from_date,
        to_date=to_date,
        provider_id=provider_id,
        q=q,
    )
    # One ENTRY_VIEWED per call regardless of page size (#45 acceptance) —
    # this describes the query, not a row, so `resource_id` is patient-level
    # (None) and the entry-type filter (when the caller narrowed by one) is
    # the only per-request detail worth keeping.
    await audit_service.emit(
        session,
        actor=actor,
        action=AuditAction.ENTRY_VIEWED,
        resource_type="medical_entry",
        resource_id=None,
        patient_id=patient_id,
        outcome=AuditOutcome.SUCCESS,
        metadata=AuditMetadata(
            entry_type=entry_type.value if entry_type is not None else None,
            count=len(rows),
        ),
    )
    provider_names = {
        pid: await _provider_name(session, pid)
        for pid in {r.source_provider_id for r in rows}
        if pid is not None
    }
    return Page[EntrySummary](
        items=[
            projections.to_summary(

19 named audit actions. The event model captures actor, action, resource, outcome and request context. Audit model / Audit fields and projection

Chapter 8

One entry trunk, five typed branches

Patient is the aggregate root. Each Medical Entry has a shared identity and timeline fields, then exactly one subtype table stores the fields for its kind.

Joined-table inheritance keeps common fields together while typed columns remain queryable. A subtype row uses the same primary key as its row in medical_entry. Each entry can have multiple Medical Documents in a separate metadata table; their bytes live behind the storage adapter.

Patient and Medical Entry joined-table inheritance Patient has many Medical Entry rows. Each row connects to exactly one of five subtype tables. Medical Document rows attach to an entry. patientaggregate root / 1 → many medical_entryid / patient_id / entry_typeoccurred_at / recorded_at / superseded_by_id diagnosisdiagnosisentry-specific fieldsprocedureprocedureentry-specific fieldsprescriptionprescriptionentry-specific fieldslab_reportlab_reportentry-specific fieldsclinical_noteclinical_noteentry-specific fields medical_document metadata

Subtype fields stay typed

DIAGNOSIS
diagnosis
code_system / code / display_name
PROCEDURE
procedure
code_system / code / display_name
PRESCRIPTION
prescription
medication_name / dosage / frequency / route
LAB REPORT
lab_report
value_numeric / value_text / unit / reference_low / reference_high
CLINICAL NOTE
clinical_note
text

Two boundaries protect meaning

Clinical fields are not metadata. The entry JSONB column holds provenance such as an import batch or source filename. Clinical values belong in typed subtype columns.

Clinical time is not recorded time. The timeline uses occurred_at; recorded_at tells when the row entered Pulse.

A Patient may be unclaimed. The Patient's User link is nullable, which lets Provider Staff file for someone before registration.

Why joined tables / Model implementation
backend/app/modules/records/models.py, lines 49-94
Inspect the source excerpt
PGUUID(as_uuid=True),
        ForeignKey("provider.id", ondelete="SET NULL"),
        default=None,
    )
    author_user_id: Mapped[uuid.UUID | None] = mapped_column(
        PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="SET NULL"), default=None
    )
    occurred_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
    recorded_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
    is_critical: Mapped[bool] = mapped_column(Boolean, server_default=func.false())
    superseded_by_id: Mapped[uuid.UUID | None] = mapped_column(
        PGUUID(as_uuid=True),
        ForeignKey("medical_entry.id", ondelete="SET NULL"),
        default=None,
    )
    entry_metadata: Mapped[dict[str, Any]] = mapped_column("metadata", JSONB, default=dict)

    __mapper_args__ = {
        "polymorphic_on": entry_type,
        "polymorphic_identity": "medical_entry",
    }


def _subtype_pk() -> Mapped[uuid.UUID]:
    return mapped_column(
        PGUUID(as_uuid=True),
        ForeignKey("medical_entry.id", ondelete="CASCADE"),
        primary_key=True,
    )


class Diagnosis(MedicalEntry):
    __tablename__ = "diagnosis"

    id: Mapped[uuid.UUID] = _subtype_pk()
    code_system: Mapped[str] = mapped_column(String(255))
    code: Mapped[str] = mapped_column(String(64))
    display_name: Mapped[str] = mapped_column(String(512))

    __mapper_args__ = {"polymorphic_identity": EntryType.DIAGNOSIS}


class Procedure(MedicalEntry):
    __tablename__ = "procedure"

Chapter 9

An insight is computed for the reader

Pulse does not store a second, precomputed version of a Patient's history. Analytics are derived when requested through the same access filter as clinical entries.

A Clinician with consent for lab reports must not receive a trend built from entries outside that scope. Computing each response for its reader keeps consent enforcement attached to the underlying rows.

The Patient dashboard presents lab trends, visits, medications, Provider contributions and informational data-quality flags. The flags identify missing or implausible identity data, long-unclaimed Patients and future-dated entries. They do not block an action. These summaries are not a source of clinical truth.

For a numeric lab result, an abnormal flag compares that value with the reference bounds on that result's own row. A text result or missing bounds cannot be compared numerically.

Why there is no Summary Insight table
Patient analytics page with a lab trend chart, summary measures and data-quality flags
One authorized requestOne derived response
  1. 01Check Patient accessauthorize_patient_access
  2. 02Audit the queryANALYTICS_VIEWED
  3. 03Filter source rowsaccessible_entries(actor, patient_id)
  4. 04Compute the seriesno summary_insight table

What the backend can derive

Lab and vital trends
coded Lab Report rowsvalues ordered by occurred_at
Visits by month
accessible Medical Entriesmonthly visit counts
Active medications
accessible prescriptionsmedication summary over a date window
Provider contributions
accessible Medical Entriesentry counts by source Provider
backend/app/modules/records/repository.py, lines 448-466
Inspect the source excerpt
# class: joining the ORM entity here pulls in its *full* joined-table-
    # inheritance selectable (`medical_entry JOIN lab_report`, aliased),
    # which then has no join condition back to the outer `medical_entry`
    # from `accessible_entries` — an unconstrained cross join that
    # silently multiplies every row.
    lab_report = LabReport.__table__
    stmt = (
        _in_window(await accessible_entries(session, actor, patient_id), from_date, to_date)
        .with_only_columns(
            MedicalEntry.occurred_at,
            lab_report.c.value_numeric,
            lab_report.c.value_text,
            lab_report.c.unit,
            lab_report.c.reference_low,
            lab_report.c.reference_high,
        )
        .join(lab_report, lab_report.c.id == MedicalEntry.id)
        .where(
            MedicalEntry.entry_type == EntryType.LAB_REPORT, MedicalEntry.superseded_by_id.is_(None)

Every series reads from the permission-filtered entry query. Analytics service / Data model notes

Chapter 10

A match becomes a question for a person

Duplicate detection compares Patient identities and creates a review item. It never merges automatically, because a wrong merge can attach one person's medical history to another.

Candidate blocking uses a trigram-name hit, shared birth year or matching phone. A shortlisted pair is scored with name similarity, date-of-birth similarity and phone equality, weighted 0.5, 0.3 and 0.2. Scores at or above 0.5 enter the review queue.

Names are lowercased, punctuation is split, and tokens are sorted before padded-trigram similarity is measured. That lets regional name-order differences surface for review.

The seeded examples below are entirely synthetic. Select one to see the same scoring rule used by the backend. A score suggests review; an Administrator makes the decision.

Why merge decisions must be human and reversible
Administrator duplicate review queue showing identity fields and entry counts, without clinical contents
Administrator dashboard with operational counts and a route to duplicate review

Duplicate detection runs on the seeded Patients at first boot. Pending candidates are ordered by score. The two planted sibling near-misses fall below the threshold, so they test precision without entering the queue.

Synthetic seed identities

Patient Aଶ୍ରୀମତୀ ଭବାନୀ ଦେବି1976-12-07 / +91 90000 79547
Patient Bଦେବି ଶ୍ରୀମତୀ ଭବାନୀ1976-12-07 / +91 90000 79547
Similarity1.000
Queue threshold0.500

Candidate for human review

Known duplicate planted in the seed set. The match does not merge these Patients.

What the queue exposes

The Administrator sees names, date of birth, phone, claimed state and entry counts. Clinical contents stay outside this screen. The Administrator can mark a pair as not duplicate or choose which Patient identity survives a merge.

A merge is permitted only when the losing Patient is unclaimed and has no live grants, and neither identity is already merged. Pulse tombstones the losing identity and keeps a record of moved entries. An Administrator can reverse the merge; later conflicting changes can prevent reversal.

Scoring and review logic / Admin identity projection / Domain model

Chapter 11

The demo data is synthetic and reproducible

Pulse's committed seed combines Synthea clinical content with a deterministic Indian identity overlay, then adds known duplicate and near-miss pairs for review.

No real Patient data enters this application. The seed makes the demo useful without presenting invented records as real history: clinical rows keep their Synthea vocabulary codes, while identity fields are overlaid for the project's Indian demographic.

Generation is pinned to Synthea v4.0.0, a patient seed of 424242, an overlay seed of 20260901 and a source population of 120. The transformed CSV files are committed, so the app does not need Java at startup.

The phone prefix +91 90000 is a Pulse convention for synthetic data. The repository does not claim that a regulator has reserved it.

How the seed is built and regenerated
Patient timeline populated with synthetic seeded medical entries
Synthetic planted candidates in the duplicate review queue
  1. GenerateSyntheacoded clinical rows
  2. OverlayIndian identitysame fixed seed
  3. PlantKnown pairsduplicates and near-misses
  4. CommitCSV datasetreproducible input
  5. LoadFirst bootidentity + capped entries

The first-boot loader selects a capped set of entries per Patient and records a seed marker so another run is a no-op.

Committed clinical source rows

These counts describe CSV rows in the repository. The loader selects a capped set for first boot.

125 Patient identities, including 37 Unclaimed Patients

  • Conditions3,908
  • Encounters6,290
  • Medications5,122
  • Observations73,845
  • Procedures13,226

3 known duplicate pairs and 2 deliberate near-miss pairs are planted in identity data. The near-misses make false positives visible during review.

backend/app/db/seed_loader.py, lines 433-461
Inspect the source excerpt
async def run_seed() -> SeedResult:
    identity_dir = _data_dir() / "identity"
    clinical_dir = _data_dir() / "clinical"
    if not (identity_dir / "patients.csv").is_file():
        raise FileNotFoundError(f"seed dataset not found under {identity_dir}")

    async with async_session() as session:
        if await _already_loaded(session):
            return SeedResult(skipped=True, counts={})

        objects, counts = _build_objects(identity_dir)
        session.add_all(objects)
        await session.flush()  # Patients committed to the flush before entries FK to them

        patient_ids = [r["id"] for r in _rows(identity_dir / "patients.csv")]
        provider_ids = [uuid.UUID(r["id"]) for r in _rows(identity_dir / "providers.csv")]
        entry_objects, entry_counts = _build_clinical_entries(
            clinical_dir, patient_ids, provider_ids
        )
        counts.update(entry_counts)
        session.add_all(entry_objects)
        await session.flush()

        await session.execute(
            text("INSERT INTO seed_marker (id, dataset_sha256) VALUES (1, :h)"),
            {"h": _dataset_checksum(identity_dir, clinical_dir)},
        )
        # Flag (never merge) planted duplicates so /admin/duplicates is populated.
        # record_duplicate_candidates commits per call, so the marker goes in first:

Dataset manifest / Deterministic overlay and pair planting / ADR-0015

Chapter 12

One application, with boundaries that matter

Pulse is a domain-organized modular monolith: one FastAPI process, one PostgreSQL database, and explicit service seams between ten business modules. The structure keeps the access rules close to every clinical read without adding a network hop for each boundary.

A microservice split would add deployment and coordination costs before Pulse has a scaling need. Modules therefore share a deployable unit, but reach other domains through service interfaces rather than directly querying their tables. The rule is enforced with a cross-module import lint.

In the data layer, Patient is the aggregate root: medical entries, Consent and audit scope all attach to a Patient identity. The clinical entry is a shared base row joined to one of five typed detail tables.

Architecture notes. Module source

One origin routes two kinds of traffic

Caddy forwards /api/* to FastAPI and the rest to Next.js. Locale middleware skips API paths. The browser uses a same-origin HttpOnly cookie session.

Caddyfile, lines 1-10
Inspect the source excerpt
:80 {
	handle /api/* {
		request_body {
			max_size 27MB
		}
		reverse_proxy backend:8000
	}

	handle {
		reverse_proxy frontend:3000

Consent travels into the query

Move through the request path. Every stage below remains readable without JavaScript.

Example endpointGET /api/v1/patients/7f3c…/entries

01The request

GET /api/v1/patients/{id}/entries

The browser sends the localized page's API request with its HttpOnly session cookie. Caddy keeps the app and API on one origin.

02The route

requires(Permission.RECORDS_READ)

FastAPI authenticates the session and checks whether this role may use the records endpoint. That check is necessary, but it does not give a Clinician access to any Patient.

03The service

list_timeline(session, actor, patient_id, …)

The records service resolves the Patient relationship, validates the request window, delegates the read and emits one access event for the request.

04The repository

accessible_entries(session, actor, patient_id)

The query builder composes the actor's applicable row filter. For a Clinician, the live Consent predicate checks expiry, entry kinds and clinical date range inside SQL.

05The result

filtered rows + request audit

Only the selected rows are serialized. Missing and inaccessible records share a 404 response, while the Patient-facing audit view contains access metadata, not clinical content.

The enforcement point is visible in code

The route declares role authorization; the repository returns a composable SQL filter with Consent conditions. The two checks answer different questions.

ADR-0004: default-deny routes. ADR-0006: one clinical query builder

backend/app/modules/records/routes.py, lines 25-47
Inspect the source excerpt
EntryCreate,
    EntryDetail,
    EntryProvider,
    EntrySummary,
)

router = APIRouter(prefix="/api/v1", tags=["records"])

SessionDep = Annotated[AsyncSession, Depends(get_session)]
CurrentUser = Annotated[AuthContext, Depends(current_user)]
StorageDep = Annotated[StorageProvider, Depends(get_storage_provider)]


@router.get(
    "/patients/{patient_id}/entries",
    dependencies=[requires(Permission.RECORDS_READ)],
)
async def list_patient_entries(
    patient_id: UUID,
    ctx: CurrentUser,
    session: SessionDep,
    entry_type: Annotated[EntryType | None, Query(alias="entryType")] = None,
    from_date: Annotated[date | None, Query(alias="fromDate")] = None,
backend/app/modules/records/repository.py, lines 106-134
Inspect the source excerpt
if await actor_owns_patient(session, actor, patient_id):
        conditions.append(MedicalEntry.patient_id == patient_id)

    provider_id = await provider_id_for_staff_actor(session, actor)
    if provider_id is not None:
        conditions.append(
            and_(
                MedicalEntry.patient_id == patient_id,
                MedicalEntry.source_provider_id == provider_id,
            )
        )

    if actor.role is Role.CLINICIAN:
        conditions.append(
            and_(
                MedicalEntry.patient_id == patient_id,
                consent_service.clinical_access_predicate(
                    patient_id,
                    actor.user_id,
                    MedicalEntry.entry_type.__clause_element__(),
                    MedicalEntry.occurred_at.__clause_element__(),
                ),
            )
        )

    if not conditions:
        conditions.append(false())

    return select(MedicalEntry).where(or_(*conditions))

Chapter 13

Patterns keep the boundaries useful

The code uses a small set of patterns for clear jobs. Each one carries a cost, and the enforcement tools make its boundary visible.

Modular monolith

Business domains share one deployable FastAPI application, while their service interfaces hide table ownership. The result is a practical local deployment with boundaries that can be checked in code.

Allowed seamapp.modules.consent.service

Rejected shortcutapp.modules.consent.repository

Contracts merge before implementations

The import lint checks the rule

A module may import another module's service, schemas or dependency seam. It may not reach into that module's models or repository. A second lint rejects raw SQL from module code, where SQL would bypass ownership again.

Read the cross-module import lint

backend/scripts/lint_cross_module_imports.py, lines 20-47
Inspect the source excerpt
_BACKEND_DIR = Path(__file__).resolve().parents[1]
_MODULES_DIR = _BACKEND_DIR / "app" / "modules"
_ALLOWED_SUBMODULES = {"service", "schemas", "dependencies"}


def _own_module(path: Path) -> str:
    """`app/modules/auth/foo/bar.py` -> `auth`."""
    return path.relative_to(_MODULES_DIR).parts[0]


def _package_parts(path: Path) -> list[str]:
    """Dotted package of the file, e.g. `['app', 'modules', 'auth']`."""
    rel = path.relative_to(_BACKEND_DIR).with_suffix("")
    parts = list(rel.parts)
    if parts[-1] == "__init__":
        parts.pop()
    else:
        parts.pop()  # drop the module filename; keep the package
    return parts


def _resolve(node: ast.ImportFrom, path: Path) -> str | None:
    if node.level == 0:
        return node.module
    base = _package_parts(path)
    # level 1 == current package, level 2 == parent, ...
    trimmed = base[: len(base) - (node.level - 1)] if node.level > 1 else base
    return ".".join(trimmed + ([node.module] if node.module else []))
Pattern, concrete use, and the trade-off it brings
PatternWhere it appearsWhy it fits hereCost to keep visible
Layered services routes.py parses and delegates; service.py applies domain rules; repository.py owns SQL. Consent checks and correction rules can be exercised without putting business decisions in HTTP handlers. More files and explicit interfaces. Lints keep SQL and cross-domain table access from slipping into the wrong layer.
Repository query object accessible_entries(actor, patient_id) returns a composable SQLAlchemy filter. Timeline, details, documents and analytics can reuse one clinical access predicate. Every clinical read must start with the builder; CI's entry-query lint checks that convention.
Ports and adapters StorageProvider, NotificationProvider and IdentityProvider separate service code from local file and SMTP implementations. Tests can supply fakes; the local demo uses a mounted filesystem and Mailpit. Interfaces add indirection. S3, SMS and ABHA remain possible substitutions, not shipped integrations.
Joined-table inheritance One medical_entry row joins one subtype table for Diagnosis, Prescription, Lab Report, Procedure or Clinical Note. Shared patient, provenance and correction fields stay uniform while each kind has typed fields. Mixed timelines need polymorphic loading. SQLAlchemy's selectin_polymorphic loads subtype details without one lazy query per row.
Append-only audit Services emit explicit events; a database grant denies UPDATE and DELETE to the application role. Reads create no ORM write to hook, so the service records them at the access point. Every read path must emit deliberately and transactionally; coverage is tested and reviewed.

One shared trunk, five clinical shapes

The base row carries identity, Patient, type and clinical timestamps. A subtype table carries the fields that make sense for that kind. A correction inserts a replacement and marks its predecessor superseded.

ADR-0001 explains the alternatives and the polymorphic loading trade-off.

backend/app/modules/records/models.py, lines 30-58
Inspect the source excerpt
class EntryType(StrEnum):
    DIAGNOSIS = "DIAGNOSIS"
    PRESCRIPTION = "PRESCRIPTION"
    LAB_REPORT = "LAB_REPORT"
    PROCEDURE = "PROCEDURE"
    CLINICAL_NOTE = "CLINICAL_NOTE"


class MedicalEntry(Base):
    __tablename__ = "medical_entry"

    id: Mapped[uuid.UUID] = mapped_column(
        PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    patient_id: Mapped[uuid.UUID] = mapped_column(
        PGUUID(as_uuid=True), ForeignKey("patient.id", ondelete="CASCADE")
    )
    entry_type: Mapped[EntryType] = mapped_column(SAEnum(EntryType, name="entry_type"))
    source_provider_id: Mapped[uuid.UUID | None] = mapped_column(
        PGUUID(as_uuid=True),
        ForeignKey("provider.id", ondelete="SET NULL"),
        default=None,
    )
    author_user_id: Mapped[uuid.UUID | None] = mapped_column(
        PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="SET NULL"), default=None
    )
    occurred_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
    recorded_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()

These are implementation boundaries, not claims of formal verification. The codebase contains 11 modules; the architecture guide describes which seams the lints can and cannot enforce.

Chapter 14

The stack follows the shape of the problem

Pulse needs typed clinical records, live row-level access checks, and a demo that boots locally. The choices below support those constraints, with their operating limits stated plainly.

Each layer has one job: a localized web app, a Python API that owns domain rules, durable relational state, short-lived session state, and one proxy in front. Docker Compose brings the six local services up together.

Pinned versions and known version traps

Next.js 16.3.2

React, TypeScript, next-intl and Tailwind build the localized App Router screens. The API contract is generated for the frontend, so request and response shapes are shared rather than retyped by hand.

Why it fits: the UI has route-level locale segments and forms that consume a typed JSON API.

FastAPI 0.141.1

Python services enforce consent and orchestration. Pydantic defines the API boundary; asynchronous SQLAlchemy repositories own database queries.

Why it fits: business rules stay testable in services, while API routes handle HTTP parsing and delegation.

PostgreSQL 18.6

Durable identity, clinical entries, Consent, notifications and audit events live in relational tables. Redis holds opaque sessions, throttling counters and expiring verification challenges.

Why it fits: the clinical data and authorization predicates need transactional, queryable state. Redis is explicitly not a source of truth.

Compose + Caddy

One local reverse proxy sends API and page traffic to their services on the same origin. Mailpit catches demo email without external credentials; uploaded documents persist in a named volume.

Why it fits: reviewers can reproduce the synthetic demo with Docker on a laptop.

Versions are part of the design

All pinned runtime and library versions are listed in the repository's tech-stack note. One deliberate constraint is TypeScript 6.0.3: the pinned type-aware ESLint tooling excludes TypeScript 6.1 and 7, so using “latest” would break the lint contract.

The codebase also documents version-specific traps for PostgreSQL 18's volume layout and Next.js build environments. Those notes make the local setup reproducible; they do not establish a production deployment.

Open the version notes. ADR-0012: same-origin routing. ADR-0005: Redis's boundary.

frontend/src/i18n/routing.ts, lines 1-8
Inspect the source excerpt
import { defineRouting } from "next-intl/routing";

// Full target is four locales (en, hi, ta, ml) per CONTEXT.md.
export const routing = defineRouting({
  locales: ["en", "hi", "ta", "ml"],
  defaultLocale: "en",
});
compose.yaml, lines 61-90
Inspect the source excerpt
postgres:
    image: postgres:18.6
    environment:
      POSTGRES_DB: pulse
      POSTGRES_USER: pulse
      POSTGRES_PASSWORD: pulse
    volumes:
      - pulse_pgdata:/var/lib/postgresql
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U pulse -d pulse"]
      interval: 5s
      timeout: 5s
      retries: 10

  redis:
    image: redis:8.8.2
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 5s
      retries: 10

  mailpit:
    image: axllent/mailpit:v1.31.0
    ports:
      - "8025:8025"

volumes:
  pulse_pgdata:
  pulse_uploads:

Use it for: a synthetic-data academic demonstration, local development and review.

Before external hosting: HTTPS, production frontend serving, trusted proxy configuration, external secrets and rehearsed database plus upload restore are open work.

Read the verified scope and remaining operations work.

Backend packages

  • Python3.13
  • FastAPI0.141.1
  • SQLAlchemy (async)2.0.52
  • Pydantic2.13.4
  • Alembic1.19.1
  • pwdlib[argon2]0.3.1
  • asyncpg0.31.0

Frontend packages

  • Next.js (App Router)16.3.2
  • React19.2.8
  • TypeScript6.0.3
  • next-intl4.13.7
  • Tailwind CSS4.3.3
  • Radix UI / shadcn1.6.7
  • Recharts3.8

Local services

  • PostgreSQL18.6
  • Redis8.8.2
  • Caddy2.11.4
  • Mailpit1.31.0

Verification tools

  • pytest + testcontainers9.1.1 / 4.15.0
  • Playwright1.63.0
  • ruff + mypy0.16.4 / 2.3.1

Opaque sessions simplify invalidation; Consent still comes from the database

Pulse stores a hash-keyed session in Redis, which makes session invalidation straightforward. JWTs would not remove the database read required to check whether Consent is live. The clinical query consults current Consent-derived permission rows in PostgreSQL on each request, whatever session token format is used.

ADR-0003 records the session choice and trade-off

Chapter 15

The interface changes language; clinical facts stay put

English, Hindi, Tamil and Malayalam have locale-prefixed routes and feature-based message catalogs. Diagnosis text, medication names and note text are shown exactly as recorded in every locale.

Translate the controls around the record

The selector below swaps between real seeded timeline captures. The page label changes with the chosen locale. The same synthetic Diagnosis remains visible in English because translating clinical content would create a new claim.

Example Diagnosis in the synthetic demo Type 2 diabetes mellitus

/en/timeline/hi/timeline/ta/timeline/ml/timeline

ADR-0013: machine-readable errors. Locale review record

Choose a captured timeline language

Your timeline

English interface screenshot of a synthetic Patient timeline. Clinical content remains in its recorded language.
Hindi interface screenshot of a synthetic Patient timeline. Clinical content remains in its recorded language.
Tamil interface screenshot of a synthetic Patient timeline. Clinical content remains in its recorded language.
Malayalam interface screenshot of a synthetic Patient timeline. Clinical content remains in its recorded language.

The routing protects the API boundary

Locale paths are defined in the routing config. The middleware matcher excludes /api, because Caddy sends API requests to FastAPI on the same origin. Indian number and date formatting uses the platform's Intl conventions.

4 localesen, hi, ta, ml

17 message files per localeFeature namespaces keep translation edits apart.

707 leaf keysAutomated key checks catch missing strings.

Chapter 16

Sixteen decisions, written down with their trade-offs

Each architecture decision record says what was chosen, what it was chosen over, and what it now costs. Open one to read the short version; the guide has the full text.

Who may read

Sessions, route guards, the one query builder, and the people the model refuses to trust.

  • 0003 Sessions are opaque tokens in Redis, not JWTs.
    Chosen over
    JWTs, which stay valid until they expire. Immediate revocation would need a server-side denylist, which is session state again.
    What it costs
    Redis becomes load-bearing for login: wipe it and everyone logs in again. The token is stored under its SHA-256, so a dump yields no usable sessions.

    Read ADR-0003 in the guide

  • 0004 Every route declares a permission or an explicit public marker, and a test fails CI if one declares neither.
    Chosen over
    Convention and code review. The realistic failure is a missing check on an endpoint added late, which only a red build always catches.
    What it costs
    The test had to exist before the modules did: introduced against three endpoints it is free, retrofitted against sixty it invites marking things public.

    Read ADR-0004 in the guide

  • 0006 Consent is part of the SQL, built in one function: accessible_entries(actor, patient_id).
    Chosen over
    Scattered checks, and Postgres row-level security, which needs per-request SET LOCAL variables that interact badly with connection pooling.
    What it costs
    Enforcement is a lint plus negative integration tests, not a formal guarantee. No permission decision may be cached, and analytics must compose from the same builder.

    Read ADR-0006 in the guide

  • 0007 The Administrator role grants no access to Medical Entries or Documents at all.
    Chosen over
    Administrator as superuser. That is how hundreds of staff end up able to read one person's file, and it makes the consent model decorative.
    What it costs
    No administrative override exists. The emergency path is break-glass, invoked by a clinician, time-boxed, justified and visible to the patient.

    Read ADR-0007 in the guide

  • 0010 A Patient consents to a named Clinician, never to a Provider organisation.
    Chosen over
    Organisation-level grants, where consenting to a hospital means thousands of people can read the record.
    What it costs
    A Clinician who changes Provider keeps their consents. A patient seen by several doctors at one hospital grants several consents, which the ADR accepts.

    Read ADR-0010 in the guide

How clinical data is stored

The shape of the record, and what is deliberately not stored.

  • 0001 One medical_entry trunk table plus one table per entry kind.
    Chosen over
    A single wide table with about 25 nullable columns, and a JSONB payload, which makes lab trends a cast and lets "120/80" land where a number belongs.
    What it costs
    Timeline reads cost one query for the trunk plus one per kind present: at most six indexed queries for a 50-entry page, flat in page size.

    Read ADR-0001 in the guide

  • 0002 Patient is the aggregate root. There is no separate Patient Record entity.
    Replaces
    The earlier design, a strict one-to-one Patient Record, which cost a join on every read and gave one concept two names.
    What it costs
    patient.user_id is nullable and load-bearing: it is what lets a Provider file for someone who has never registered. It must not be tidied into a required column.

    Read ADR-0002 in the guide

  • 0009 Analytics are computed per request, through the consent filter. There is no Summary Insight table.
    Chosen over
    A stored insight row, which is computed once without an actor and so is either unfiltered or recomputed per actor anyway.
    What it costs
    Every analytics query composes from accessible_entries. If a chart is ever slow, the answer is a Postgres materialised view, not Redis.

    Read ADR-0009 in the guide

  • 0015 Seed data is Synthea output with a deterministic Indian identity overlay, committed to the repo.
    Chosen over
    Hand-written histories, and regenerating on setup, which would need a JDK on every machine before git clone and docker compose up could work.
    What it costs
    The dataset is megabytes of CSV that diff review will not inspect. Regeneration is pinned to a Synthea version and seeds. Planted near-misses make detection precision measurable.

    Read ADR-0015 in the guide

Keeping history honest

The audit log, merges, and what happens inside a transaction.

  • 0008 The application's database role holds INSERT and SELECT on audit_event and nothing else.
    Chosen over
    "We simply don't update that table", which is an intention that lasts until someone writes a cleanup script.
    What it costs
    Two database roles exist from the first migration. Audit corrections are impossible by design: a wrong event is fixed by writing a new one.

    Read ADR-0008 in the guide

  • 0011 Duplicate detection only creates a review item. A person merges, and every merge records enough to be undone.
    Chosen over
    Merging automatically above a similarity score. A missed duplicate is an inconvenience; a wrong merge is a patient-safety incident.
    What it costs
    The losing Patient is tombstoned with merged_into_id, never deleted. ADR-0016 later made reversal conditional on nothing having been built on the merge.

    Read ADR-0011 in the guide

  • 0016 A clinical operation commits its change, its audit event and its in-app notification together, and a clinical read commits its audit event first.
    Tightens
    The unconditional reversibility wording of ADR-0011: reversal now fails with a coded 409 if later corrections or documents depend on the merge.
    What it costs
    If the audit write fails, the read fails. Email still runs after the commit and is best effort, because guaranteed delivery would need a durable outbox.

    Read ADR-0016 in the guide

  • 0017 Break-glass reveals only a Patient-written emergency card, not the record. A QR opens the same card for any signed-in user, audited each time.
    Replaces
    Unscoped record access without consent for 60 minutes, which break-glass used to mean.
    What it costs
    A Clinician who needs records in an emergency still needs consent; the card carries what is safe to share without it.

    Read ADR-0017 in the guide

  • 0018 A patient can ask questions of their own record. A fixed intent matcher answers them through the existing services, nothing is stored, and each answer shows what it was read from.
    Replaces
    A language model that retrieves and summarises, which cannot be shown to respect the consent filter.
    What it costs
    Coverage is bounded by the phrase lexicons, and the Hindi, Tamil and Malayalam ones are unreviewed.

    Read ADR-0018 in the guide

How the pieces fit

Infrastructure and contract choices that look like plumbing and are not.

  • 0005 Redis holds sessions, rate limits and short-lived tokens. Never a source of truth.
    Chosen over
    Letting a cache grow into patient lists and denormalised timelines, each of which looks reasonable alone.
    What it costs
    Anything that must survive a restart lives in PostgreSQL. Consent stays in Postgres even though checking it from a cache would be faster.

    Read ADR-0005 in the guide

  • 0012 Caddy serves the frontend and the API from one origin, everywhere.
    Chosen over
    Next.js and FastAPI on separate ports with CORS written to paper over it. Cross-origin cookies force SameSite=None, then Secure, then HTTPS on a laptop.
    What it costs
    Caddy is in the request path even locally, and the next-intl middleware matcher must exclude /api or every API call breaks.

    Read ADR-0012 in the guide

  • 0013 The API returns error codes, never user-facing strings.
    Chosen over
    Returning renderable English, which is untranslatable across four locales without touching every endpoint.
    What it costs
    Codes are a permanent contract and are never reworded. The enum is exported through OpenAPI and generated into a TypeScript union.

    Read ADR-0013 in the guide

  • 0014 Pydantic schemas are the contract, and stub endpoints ship before implementations.
    Chosen over
    A hand-maintained OpenAPI file, which drifts from the code within a fortnight, and a frontend waiting on finished handlers.
    What it costs
    The schema merge becomes the real integration gate, so schemas get reviewed harder than handlers. CI prints the stub inventory on every run.

    Read ADR-0014 in the guide

18 records in docs/adr. Some exist only to stop an old argument from restarting: 0002 and 0003 both say they are recorded because someone will propose the other option again.

Chapter 17

The tests are written to fail when the filter is missing

Pulse's risk is one question: did the consent filter apply to that query. A mocked database cannot answer it, so the tests do not use one.

The backend suite starts real PostgreSQL and Redis in containers (testcontainers) and runs 312 tests against them. Most are integration tests. Unit tests are kept for branchy logic that needs no database, such as permission resolution, duplicate scoring and consent expiry.

Negative tests come first. A positive test, where a consented Clinician sees the entry, passes just as happily when the filter was never applied, because the entry comes back either way. These are the tests that matter most here.

LayerRuns againstSize
Backend suite Real PostgreSQL and Redis, started by testcontainers 312 tests
Browser suite, mocked Chromium with /api/v1/** stubbed 80 tests in 15 specs
Live spine The full Compose stack through Caddy, nothing mocked 1 spec

What CI runs on every pull request

Four jobs run in parallel, from .github/workflows/ci.yml. Steps tagged lint are the enforcement checks: each one fails the build on an absence that review tends to miss.

  1. backend

    Real PostgreSQL and Redis, started by testcontainers

    1. uv sync --frozen --group dev Install pinned dependencies
    2. generate_api.py --check OpenAPI and generated TypeScript types agree
    3. ruff check . Lint
    4. mypy . Types
    5. lint_cross_module_imports.py No domain reaches into another's tables lint
    6. lint_module_sql.py No raw SQL in domain modules lint
    7. lint_entry_query.py No select(MedicalEntry) outside the query builder lint
    8. lint_actor_first.py Readers of personal data take an actor lint
    9. stub_inventory.py Print remaining stub endpoints
    10. pytest Integration suite against real containers test
  2. frontend

    No server needed

    1. npm ci Install pinned dependencies
    2. npm run check:locales Same keys and interpolations in all four locales
    3. npm run lint ESLint
    4. npx tsc --noEmit Types
    5. npm run build Production build
  3. frontend-e2e

    Playwright with the API mocked

    1. npm ci Install
    2. playwright install chromium Browser
    3. playwright test Mocked browser suite test
  4. e2e-live

    The whole stack, nothing mocked

    1. docker compose up --build -d --wait Boot six services
    2. npm ci and playwright install Install
    3. npm run test:e2e:live Drive the real spine test
    4. docker compose logs --tail 300 Runs only on failure

What the live job exercises

  1. Provider Staff files an entry
  2. Patient grants consent, with step-up
  3. Clinician reads the record
  4. Patient sees the access in the audit log
  5. Patient revokes
  6. Clinician is locked out

The mocked suite cannot see the contract between frontend and backend: it once stayed green while every real consent grant failed for want of a password re-entry the form never sent. The live job exists because of that. See learnings.

A bad router must fail the build

ADR-0004 says every route declares a permission or an explicit public marker. The test that enforces it also proves it can fail: it mounts a router with one undeclared route on a throwaway app and asserts the check reports exactly that route. A coverage check that never fails would be indistinguishable from one that does not run.

One route is on an explicit allowlist, the unauthenticated liveness probe GET /api/v1/health.

backend/tests/_fixtures/bad_router.py, lines 10-15
Inspect the source excerpt
router = APIRouter()


@router.get("/api/v1/deliberately-undeclared")
async def undeclared() -> dict[str, str]:
    return {"status": "undeclared"}
backend/tests/test_route_coverage.py, lines 88-101
Inspect the source excerpt
def test_coverage_check_bites_on_an_undeclared_route() -> None:
    """Positive case: a router with a deliberately undeclared route must be
    reported by the same check."""
    ...
    throwaway = FastAPI()
    throwaway.include_router(module.router)

    offending = _undeclared(throwaway)
    assert offending == ["GET /api/v1/deliberately-undeclared"]

Five of the negative tests

  • An Administrator reads nothing

    Timeline, entry detail and the audit endpoint all return 403 for an Administrator, because the role holds no clinical permission. test_phase3_adversarial_suite.py

  • A Clinician without consent gets 404

    The route lets the role through, so the denial has to come from the query builder, and it has to be a 404. test_phase3_adversarial_suite.py

  • A consent scoped to labs does not leak a note

    Granted through the real POST /consents route with step-up, not built by hand. test_phase3_adversarial_suite.py

  • The audit table refuses UPDATE and DELETE

    Run as the application role. Postgres answers "permission denied". test_consent_audit_notifications_schema.py

  • Revocation lands between building a query and running it

    The statement is built while consent is live, a second session revokes, and executing the statement returns nothing. test_architecture_regressions.py

backend/tests/test_architecture_regressions.py, lines 79-101
Inspect the source excerpt
async def test_permission_is_rechecked_when_the_statement_executes(
    db_session: AsyncSession, db_engine: AsyncEngine, app_database_url: str
) -> None:
    patient = await _patient(db_session, await _user(db_session, Role.PATIENT))
    clinician = await _user(db_session, Role.CLINICIAN)
    await db_session.commit()
    await rh.insert_entry(app_database_url, patient_id=patient.id, occurred_at=datetime.now(UTC))
    await _live_permission(
        db_session,
        patient=patient,
        clinician=clinician,
        expires_at=datetime.now(UTC) + timedelta(days=2),
    )
    await db_session.commit()
    stmt = await records_repo.accessible_entries(
        db_session, Actor(user_id=clinician.id, role=Role.CLINICIAN), patient.id
    )
    async with async_sessionmaker(db_engine)() as revoker:
        await revoker.execute(
            delete(AccessPermission).where(AccessPermission.patient_id == patient.id)
        )
        await revoker.commit()
    assert (await db_session.execute(stmt)).scalars().all() == []

The test in full. Nothing is cached: the revoker deletes the permission row, and the next execution of the query sees it gone. A statement already running when revocation commits is not interrupted, which ADR-0016 states plainly.

Chapter 18

What is different here, and what is not

None of these ideas is new on its own. What we would point a reader to is that each one is enforced by a query, a test or a database grant, so it holds when nobody is paying attention.

  1. Consent is a clause in the query, built in one place.

    accessible_entries(actor, patient_id) returns a filter that ORs together the owner, the authoring provider and the consent predicate, and falls back to false() when none applies. A lint fails the build on select(MedicalEntry) anywhere else. The lint is a textual pattern, so this is a strong convention and not a formal guarantee, which ADR-0006 says outright.

  2. A denied read looks like a patient who does not exist.

    A Clinician with no consent gets 404 on the timeline and on entry detail, not 403, because a 403 would confirm the person is a patient at all. An adversarial test asserts it for both routes.

  3. Revoking consent deletes a row. Nothing is cached to expire.

    Revocation stamps the consent and deletes its derived permission row in the same transaction, so the next query that starts after the commit is denied. Pulse caches no permission decision. A statement already executing when the revoke commits is not interrupted, and data already returned cannot be taken back.

  4. The Administrator role holds no clinical permission.

    It lacks RECORDS_READ, so the timeline, entry detail and audit endpoints return 403 for it. The duplicate-review screen shows identity fields and an entry count. That count is the one deliberate bypass of the query builder, gated to Administrators in the service and recorded in the learnings as a narrow exception. An administrator audit viewer is not implemented.

  5. The application cannot edit its own audit log.

    The application's database role holds INSERT and SELECT on audit_event and nothing more, and migrations run as a separate owner role. Tests run UPDATE and DELETE as the application role and expect "permission denied". A wrong event is fixed by writing another.

  6. Audit and notification payloads have a deliberately closed shape.

    emit() accepts an AuditMetadata with four declared fields rather than an arbitrary dictionary. Notification params reject extra fields and allow only a count and typed identifiers. Clinical contents must never be copied into either payload. The audit justification is free text, so this rule still depends on what callers and users put there.

    backend/app/modules/audit/service.py, lines 56-67
    Inspect the source excerpt
    @dataclass(frozen=True)
    class AuditMetadata:
        """The only fields `emit()` can carry into `audit_event.metadata`.
        Identifiers, counts, entry types — never a clinical value
        (clinical-safety.md, `audit/models.py`). Add a field here only for
        something that is provably non-clinical; do not widen this into a
        free-form dict."""
    
        entry_type: str | None = None
        provider_name: str | None = None
        count: int | None = None
        justification: str | None = None
  7. A Provider can file for a person who has never registered.

    patient.user_id is nullable on purpose. The seed holds 37 of its 125 Patients with no account, and Provider Staff file entries for them by Patient ID. What is not built: creating a new unclaimed Patient from the UI, and the flow by which that person later claims the record.

  8. Duplicate detection accounts for name order, and its precision is tested.

    Candidates are blocked first by a trigram hit on the name, the same birth year or the same phone. Scoring then sorts each name's tokens before comparing trigrams and weights name 0.5, birth date 0.3 and phone 0.2, with a threshold of 0.5. The seed plants 3 true duplicates and 2 look-alike pairs that are different people, and the tests expect the first flagged and the second not. Nothing merges without an Administrator.

  9. Four locales, with clinical text left exactly as recorded.

    The API returns codes and the frontend renders text from them. A CI check requires the same keys and interpolations in all four catalogs. A diagnosis reads the same in every language, because translating it would invent a medical claim. The Hindi, Tamil and Malayalam catalogs have not been reviewed by a native speaker.

Chapter 19

Contracts merged first, so four people could build in parallel

The team split the work by layer, which means no feature was finished by one person. That made the agreements between layers the most important thing to write down early.

Phase by phase, from skeleton to packaging

  1. Phase 0, bootstrap

    No closing issue recorded

    The repo skeleton in one empty commit, Compose with six services, Caddy same-origin routing, CI green on an empty repo, the error envelope, the first migration with two database roles, the Next.js shell with the locale matcher excluding /api.

    Exit: docker compose up starts six containers and CI is green.

  2. Phase 1, skeleton

    Closed by #23

    Register, verify by email, log in, see a seeded Patient, switch to Hindi. The route-coverage test, the entry-query lint and the cross-module import lint landed here, against three endpoints.

    Exit: A fresh clone boots, seeded, and logs in. Met 2026-09-08.

  3. Phase 2, records spine

    Closed by #24

    The medical_entry trunk and five subtype tables, provider upload with MIME sniffing, the patient timeline, corrections by supersession.

    Exit: A Provider's upload appears on the Patient's timeline.

  4. Phase 3, consent, audit, notifications

    Closed by #47

    accessible_entries, consent grant behind step-up and revoke without, break-glass, the append-only audit table, notifications, and the adversarial suite of negative tests.

    Exit: The whole spine works and every negative test is green. Nothing from Phase 4 started before this.

  5. Phase 4, analytics, admin, duplicates, locales

    Closed by #52 , #53 , #54 , #55

    Analytics computed on read, the administrator console with no clinical data, blocked-then-scored duplicate detection with reversible merges, Hindi, Tamil and Malayalam catalogs.

    Exit: Catalogs delivered as recorded-unverified, not reviewed by a native speaker.

  6. Phase 4.5, packaging

    Closed by #56

    The live end-to-end spec and its CI job, a rehearsal on a fresh clone, documentation consolidated.

    Exit: Closed 2026-10-14.

From the delivery plan. Phase 1 was in fact built solo against its ticket, in one contract commit and four parallel lanes, and the plan records that some solo-driven work landed as direct commits to main rather than through pull requests.

Every module passes three gates, in order

Each gate is merged code, not a conversation, and each unblocks someone. The frontend waits on schemas, never on implementations. If a screen is blocked on a finished backend, the stub was skipped and that is the bug.

  1. G1

    Contract

    Pydantic schemas merge, plus repository signatures whose bodies raise NotImplementedError. The shape is fixed.

  2. G2

    Stub

    A @stub endpoint returns fixture data matching the schema, so the frontend builds against a real HTTP response.

  3. G3

    Implementation

    Service and repository are filled in and the integration tests are green. This is what the demo runs.

The stub inventory prints on every CI run and now reports zero remaining stubs. ADR-0014 has the reasoning.

What we learned

Contracts merge before implementations.
Schemas and repository signatures first, stubs second, real code third. A person blocked waiting on someone else's implementation means a gate was skipped. Read the reasoning.
Enforcement tests are cheap early and unpayable late.
The route-coverage test, the entry-query lint and the cross-module import lint landed against three endpoints, not sixty. Read the reasoning.
Write the negative test first.
A positive test passes just as happily when the access filter was never applied. Read the reasoning.
A green mocked suite is not an integration test.
The backend required a password re-entry before granting consent, the form never sent one, every live grant failed, and CI stayed green because the mock accepted it. The live spec exists because of that. Read the reasoning.
Never state an unverified external fact in project documentation.
Two research passes hit blocked primary sources; both are recorded as unverified rather than smoothed over. This is why the locale review page says plainly that no native speaker has read the Hindi, Tamil or Malayalam. Read the reasoning.
The interface is localised; clinical data is not.
This one gets violated by accident, in the direction of helpfulness. Read the reasoning.

The team

Four people, one slice each, tracked on the build plan.

  • Shivansh Neekhra Database, ticket #18
  • Akshay VS Backend, ticket #19
  • Bharadwaj B Chand Frontend, ticket #20
  • Srimoneyshankar Ajith Platform, integration and review, ticket #21
Course
CSE312 Software Architecture Principles and Practices
Institute
Indian Institute of Information Technology, Kottayam
Guide
Dr. Dhakshayani J

Chapter 20

Questions a grader would ask

Short answers, each pointing at the document that holds the long one.

  • Why not JWT?

    Opaque sessions make login-session invalidation a server-side lookup. A self-contained JWT needs an additional check to invalidate it before expiry, and this laptop-scale deployment gains little from stateless authentication. Clinical consent is a separate database check on every read: a valid login session never substitutes for an active permission.

  • Why a modular monolith and not microservices?

    Microservices buy independent deployment and scaling, and Pulse runs as one Compose stack on a laptop with no scaling requirement. The costs would be real: network calls between domains and distributed transactions. The module boundaries are drawn as if extraction were coming, and CI lints cross-module imports and raw SQL to keep them honest.

  • How does consent revocation take effect immediately?

    Revoking stamps the consent and deletes its permission row in the same transaction. Every clinical read builds its query from accessible_entries, which checks that row, so the next statement after the commit is denied. Nothing caches a permission decision. A statement already running at the moment of revocation is not interrupted.

  • Can an administrator see my records?

    No. The Administrator role holds no clinical permission, so the timeline, entry detail and audit endpoints refuse it. The duplicate-review screen shows identity fields and a count of entries, never their contents. There is no override; the emergency route is break-glass, used by a Clinician, limited to 60 minutes and shown to you.

  • How was the dataset made, and is any of it real?

    None of it is real. Clinical content comes from Synthea v4.0.0 with a fixed seed, and a deterministic overlay replaces its American names, addresses and phone numbers with Indian ones. The phone numbers use the sentinel prefix +91 90000. The result is 125 Patients, of which 5 are planted for testing duplicate detection, and it is committed to the repository.

  • Why Synthea?

    Hand-written histories do not scale past a handful of patients and come out too clean, with every value in range. Synthea generates longitudinal records with real coded vocabularies (SNOMED CT, LOINC, RxNorm), and the analytics are only as credible as the codes underneath. It is a Java tool, so the output is committed and nobody needs a JDK to run the demo.

  • How are duplicates detected, and can a merge be undone?

    Candidates are blocked first by a trigram name hit, the same birth year or the same phone, then scored on name (0.5), birth date (0.3) and phone (0.2) against a threshold of 0.5. A match only creates a review item; an Administrator performs any merge. A merge can be reversed while nothing has been built on it, and a reversal blocked by later corrections or documents returns a coded 409 for manual review.

  • Why 404 instead of 403?

    A 403 on a patient's records says the record exists, which discloses that a named person is a patient at all. A 404 makes a denied read indistinguishable from a patient who does not exist. 403 is kept for a role that fails outright, such as an Administrator reaching a clinical endpoint.

  • Why not translate diagnoses?

    The interface is localised and clinical data is not. A Diagnosis recorded as "Type 2 diabetes mellitus" reads that way in every locale, because translating it would be inventing a medical claim. The API returns error codes so that the interface text can be translated without touching the backend.

  • Is there an AI chatbot over the record?

    There is a question box, and no model behind it. A fixed set of phrase lexicons maps a question to one of eight intents, and each intent runs an existing query through the same consent filter as the timeline. Nothing you ask is stored, an answer that reads the record is logged once with the intent name and never the question, and every answer has a receipt showing what it was read from. The cost is coverage: it answers those eight kinds of question and says so otherwise.

  • What is not implemented?

    Not built: Administrator audit viewer; User and role management; Patient search (Patients are opened by exact ID); Provider-created Patient onboarding and account claim; Password and email change; Notifications for non-Patient roles (Clinicians are emailed); SMS delivery. Hindi, Tamil and Malayalam have not been reviewed by a native speaker. No compliance certification or real-patient readiness is claimed.

  • How do I run it?

    You need Docker and free ports 80 and 8025. Clone the repository and run docker compose up --build -d --wait, then open http://localhost. The first boot migrates and seeds the database by itself; the last chapter has the commands and the demo logins.

  • What would you change for production?

    The repository's own list is HTTPS with secure cookies, production frontend serving, external credentials, a restricted trusted-proxy policy, and tested restores of the database and uploads together. Email through SMTP is best effort, and guaranteed delivery would need a durable outbox. Native-speaker locale review, load testing and an accessibility audit are also still open.

  • Where are the design decisions recorded?

    In 18 architecture decision records under docs/adr, each with its alternatives and consequences. Patterns that are not big enough for an ADR, such as repository and service layers or cursor pagination, are explained in the learnings file. The architecture page ties them together.

Chapter 21

Run it on your own machine

Everything in this story is in the repository. A clone and one Compose command bring up the same stack the tests run against.

  1. Get the code and start the stack

    You need Docker with Compose, and ports 80 and 8025 free. Always pass --build: without it Compose can reuse a stale frontend image. The first boot runs the 10 migrations and loads the seed data by itself, and a second run changes nothing.

    git clone https://github.com/moneytosms/Pulse.git
    cd Pulse
    docker compose up --build -d --wait
  2. Open it

    The app is at http://localhost, served by Caddy. Verification emails land in Mailpit at http://localhost:8025, a local inbox, so nothing leaves the machine. 6 services start: Caddy, frontend, backend, PostgreSQL 18.6, Redis 8.8.2 and Mailpit.

  3. Log in as someone

    The login page has a quick-login button for each of these accounts. They share one password, which is in RUNNING.md along with the exact walkthrough of every screen.

    RoleEmail
    Patient (English) demo.patient.en@example.com
    Patient (Hindi) demo.patient.hi@example.com
    Provider Staff staff000@example.com
    Clinician clinician0@example.com
    Administrator admin0@example.com

    Password: see RUNNING.md. All data is synthetic.

  4. Run the real spine yourself

    With the stack up, this drives a browser through file, grant with step-up, clinician read, audit, revoke and lockout against the live services, with nothing mocked. It needs Node 24.

    cd frontend
    npm ci
    npx playwright install --with-deps chromium
    npm run test:e2e:live
  5. Tear it down

    Plain docker compose down keeps the volumes. Adding -v wipes the database and uploads, and the next start reseeds from scratch.

    docker compose down -v

That is the whole story

The guide renders the repository's own documents: the decisions, the domain model, the workflows audited against the code, and the seed pipeline. The source is public.