Kulcare Docs
DeveloperCare plans

Audit Schema

Purpose: Compliance logging, activity tracking, PHI access, and AI audit trails Tenant Scoped: Yes (all tables) RLS Enabled: Yes

Overview

The audit schema provides comprehensive logging for:

  • General activity tracking
  • PHI (Protected Health Information) access for HIPAA/DPDP compliance
  • LLM/AI call logging for AI audit trails
  • Clinical document change tracking

All audit tables are append-only with long-term retention policies.

Entities

Activity Logging

Entity: ActivityLog

Purpose: General user activity tracking

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
tenant_idUUIDYesOwning tenant
user_idUUIDNoActing user
user_emailStringNoUser email (denormalized)
session_idStringNoSession identifier
actionEnumYescreate, read, update, delete, login, logout, export, print
resource_typeStringYesResource type (e.g., "Patient", "Encounter")
resource_idUUIDNoResource identifier
resource_nameStringNoResource display name
descriptionTextNoActivity description
old_valuesJSONBNoPrevious values (for updates)
new_valuesJSONBNoNew values (for updates)
metadataJSONBNoAdditional context
ip_addressStringNoClient IP address
user_agentStringNoBrowser/client info
facility_idUUIDNoFacility context
created_atTimestampYesActivity timestamp

Action Types:

  • create - Resource creation
  • read - Resource access/view
  • update - Resource modification
  • delete - Resource deletion
  • login - User authentication
  • logout - Session end
  • export - Data export
  • print - Document print
  • share - Data sharing
  • bulk_action - Bulk operations

Metadata Structure:

{
  "source": "web",
  "endpoint": "/api/patients/123",
  "method": "PATCH",
  "changes_summary": "Updated contact information",
  "duration_ms": 245
}

Relationships:

  • Belongs to: Tenant, User, Facility

PHI Access Logging

Entity: PhiAccessLog

Purpose: Protected Health Information access tracking (HIPAA/DPDP compliance)

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
tenant_idUUIDYesOwning tenant
user_idUUIDYesAccessing user
user_roleStringNoUser role at time of access
patient_idUUIDYesPatient whose data was accessed
resource_typeStringYesType of PHI accessed
resource_idUUIDNoSpecific resource
access_typeEnumYesview, download, print, share, export, amend
access_reasonEnumYestreatment, payment, operations, emergency, patient_request, audit
reason_detailTextNoDetailed reason
data_categoriesString[]NoCategories of data accessed
emergency_accessBooleanNoBreak-the-glass access
emergency_justificationTextNoEmergency justification
ip_addressStringNoClient IP
session_idStringNoSession identifier
facility_idUUIDNoFacility context
created_atTimestampYesAccess timestamp

Access Types:

  • view - Viewed patient record
  • download - Downloaded patient data
  • print - Printed patient document
  • share - Shared with another provider
  • export - Exported to external system
  • amend - Amended patient record

Access Reasons (HIPAA-aligned):

  • treatment - Treatment purposes (TPO)
  • payment - Payment processing (TPO)
  • operations - Healthcare operations (TPO)
  • emergency - Emergency access (break-the-glass)
  • patient_request - Patient-requested access
  • audit - Compliance audit
  • legal - Legal/court order
  • research - De-identified research

Data Categories:

["demographics", "conditions", "medications", "lab_results",
 "imaging", "notes", "billing", "insurance"]

Relationships:

  • Belongs to: Tenant, User, Patient, Facility

Retention: 6 years minimum (HIPAA requirement)


AI/LLM Audit Logging

Entity: LlmCallLog

Purpose: AI/LLM call audit trail for transparency and compliance

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
tenant_idUUIDYesOwning tenant
user_idUUIDNoTriggering user
facility_idUUIDNoFacility context
encounter_idUUIDNoRelated encounter
patient_idUUIDNoRelated patient
call_typeEnumYestranscription, suggestion, summary, analysis, chat
providerStringYesAI provider (openai, anthropic, google)
modelStringYesModel identifier
input_typeEnumYesaudio, text, structured
input_tokensIntegerNoInput token count
output_tokensIntegerNoOutput token count
input_hashStringNoHash of input (no PII stored)
output_summaryTextNoSummary of output (no PII)
confidence_scoreDecimalNoModel confidence
latency_msIntegerNoResponse time
statusEnumYessuccess, error, timeout, filtered
error_messageTextNoError details
moderation_flagsJSONBNoContent moderation results
cost_usdDecimalNoAPI call cost
created_atTimestampYesCall timestamp

Call Types:

  • transcription - Audio transcription (AI Scribe)
  • suggestion - Clinical suggestion generation (CDS)
  • summary - Document/encounter summarization
  • analysis - Data analysis
  • chat - Interactive AI chat
  • coding - Diagnosis/procedure coding assistance

Moderation Flags Structure:

{
  "categories": {
    "hate": false,
    "violence": false,
    "self_harm": false,
    "sexual": false
  },
  "flagged": false
}

Note: Actual PHI is NOT stored in this table. Only hashes and summaries for audit purposes.

Relationships:

  • Belongs to: Tenant, User, Facility, Encounter, Patient

Retention: 2 years minimum


Document Audit Logging

Entity: DocumentAuditLog

Purpose: Clinical document change tracking with immutability

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
tenant_idUUIDYesOwning tenant
document_typeStringYesDocument type (CarePlan, Prescription, Note)
document_idUUIDYesDocument identifier
actionEnumYescreated, amended, signed, cosigned, addendum, voided
actor_idUUIDYesUser/practitioner who acted
actor_roleStringNoActor role
previous_version_idUUIDNoPrevious version reference
change_summaryTextNoSummary of changes
change_detailsJSONBNoDetailed changes
reasonTextNoReason for change
signature_dataJSONBNoDigital signature info
is_legal_recordBooleanNoPart of legal medical record
attestationTextNoAttestation statement
created_atTimestampYesAction timestamp

Action Types:

  • created - Initial document creation
  • amended - Amendment to existing document
  • signed - Provider signature
  • cosigned - Co-signature by supervising provider
  • addendum - Addendum added
  • voided - Document voided/cancelled
  • locked - Document locked from further edits
  • unlocked - Document unlocked (emergency/correction)

Signature Data Structure:

{
  "signer_id": "uuid",
  "signer_name": "Dr. John Smith",
  "signer_credentials": "MD, FACC",
  "signed_at": "2024-01-15T10:30:00Z",
  "signature_type": "electronic",
  "certificate_hash": "sha256:..."
}

Relationships:

  • Belongs to: Tenant
  • References: Various clinical documents

Retention: Permanent (legal medical record)


Entity: ConsentAuditLog

Purpose: Patient consent tracking for DPDP/GDPR compliance

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
tenant_idUUIDYesOwning tenant
patient_idUUIDYesPatient reference
consent_typeEnumYestreatment, data_sharing, research, marketing
actionEnumYesgranted, revoked, updated
scopeJSONBNoConsent scope details
granted_toJSONBNoEntities consent given to
valid_fromTimestampNoConsent start
valid_untilTimestampNoConsent end
collection_methodEnumNowritten, electronic, verbal
witness_idUUIDNoWitness user
ip_addressStringNoIf electronic
created_atTimestampYesAction timestamp

Consent Types:

  • treatment - Consent to treatment
  • data_sharing - Share data with providers/payers
  • abdm - ABDM health data sharing
  • research - Research participation
  • marketing - Marketing communications
  • telemedicine - Telemedicine services

Relationships:

  • Belongs to: Tenant, Patient

Offline Sync Tracking

The offline sync tables track operations performed while devices are offline, enabling reliable synchronization when connectivity returns.

See Offline Mode for complete documentation.

Entity: OfflineSyncLog

Purpose: Track all operations performed offline and their sync status

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
tenant_idUUIDYesTenant reference
facility_idUUIDYesFacility where operation occurred
user_idUUIDYesUser who performed operation
device_idStringYesUnique device identifier
operation_typeEnumYescreate, update, delete
resource_schemaStringYesSchema name (clinical, billing)
resource_typeStringYesTable/entity name
resource_idUUIDYesResource identifier
payloadJSONBYesFull operation payload
client_timestampTimestampYesWhen created on client
sync_statusEnumYesqueued, received, processing, synced, conflict, failed
conflict_typeEnumNoversion_mismatch, deleted_resource, validation_error, business_rule
resolution_strategyEnumNoclient_wins, server_wins, merged, manual
error_messageTextNoError details if failed

Relationships:

  • Belongs to: Tenant, Facility, User

Entity: OfflineDevice

Purpose: Track authorized devices for offline access

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
tenant_idUUIDYesTenant reference
facility_idUUIDYesAuthorized facility
user_idUUIDYesDevice owner
device_idStringYesUnique device fingerprint
device_typeEnumYesdesktop, tablet, mobile
statusEnumYesactive, suspended, revoked
last_sync_atTimestampNoLast successful sync
token_expires_atTimestampNoToken expiration

Relationships:

  • Belongs to: Tenant, Facility, User
  • Has many: OfflineSyncLogs

Entity: SyncBatch

Purpose: Group related offline operations for atomic sync

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
tenant_idUUIDYesTenant reference
device_idStringYesOriginating device
operation_countIntegerYesNumber of operations in batch
statusEnumYespending, processing, completed, partial, failed

Relationships:

  • Belongs to: Tenant, OfflineDevice
  • Has many: OfflineSyncLogs

Schema Diagram

+---------------+       +---------------+       +---------------+
| activity_logs |       | phi_access_   |       | consent_      |
|               |       | logs          |       | audit_logs    |
+---------------+       +---------------+       +---------------+
       |                       |                       |
       v                       v                       v
+------------------------------------------------------------------+
|                     Compliance Dashboard                          |
+------------------------------------------------------------------+
       ^                       ^                       ^
       |                       |                       |
+---------------+       +---------------+       +---------------+
| llm_call_logs |       | document_     |       | offline_      |
|               |       | audit_logs    |       | sync_logs     |
+---------------+       +---------------+       +---------------+
                                                       ^
                                                       |
                                        +---------------+---------------+
                                        |                               |
                                +---------------+               +---------------+
                                | offline_      |               | sync_batches  |
                                | devices       |               |               |
                                +---------------+               +---------------+

Retention Policies

TableRetention PeriodRegulatory Driver
activity_logs2 yearsGeneral compliance
phi_access_logs6 yearsHIPAA (US), DPDP (India)
llm_call_logs2 yearsAI transparency
document_audit_logsPermanentMedical record law
consent_audit_logs6 yearsGDPR, DPDP
offline_sync_logs1 yearOperational
offline_devicesUntil revoked + 1 yearSecurity
sync_batches90 daysOperational

RLS Policies

-- All audit tables: tenant isolation
CREATE POLICY tenant_isolation ON audit.activity_logs
    USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

CREATE POLICY tenant_isolation ON audit.phi_access_logs
    USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

CREATE POLICY tenant_isolation ON audit.llm_call_logs
    USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

CREATE POLICY tenant_isolation ON audit.document_audit_logs
    USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

-- Offline sync tables: tenant isolation
CREATE POLICY tenant_isolation ON audit.offline_sync_logs
    USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

CREATE POLICY tenant_isolation ON audit.offline_devices
    USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

CREATE POLICY tenant_isolation ON audit.sync_batches
    USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

Compliance Reporting

The audit schema supports:

  1. HIPAA Compliance (USA)

    • PHI access reports
    • Breach notification data
    • Security incident tracking
  2. DPDP Compliance (India)

    • Data processing records
    • Consent management
    • Data principal access requests
  3. AI Transparency

    • LLM usage reports
    • Model decision audit
    • Bias/fairness monitoring
  4. Clinical Quality

    • Document completion metrics
    • Amendment tracking
    • Signature compliance
  5. Offline Operations

    • Sync status monitoring
    • Conflict resolution tracking
    • Device authorization audit

Security Considerations

  1. Append-Only: Audit tables should be append-only (no UPDATE/DELETE)
  2. Encryption: Sensitive fields encrypted at rest
  3. Access Control: Limited to compliance officers and admins
  4. Integrity: Checksums for tamper detection
  5. Archival: Automated archival to cold storage after retention period

Entity Summary

EntityTenant ScopedRLSDescription
ActivityLogYesYesGeneral activity tracking
PhiAccessLogYesYesHIPAA/DPDP PHI access
LlmCallLogYesYesAI/LLM call audit
DocumentAuditLogYesYesClinical document changes
ConsentAuditLogYesYesPatient consent tracking
OfflineSyncLogYesYesOffline operation tracking
OfflineDeviceYesYesAuthorized offline devices
SyncBatchYesYesAtomic sync groups

Total Tables: 8

On this page