The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
feat: add healthcare domain skills and agent
Dr. Keyur Patel63737544a18a
diff --git a/agents/healthcare-reviewer.md b/agents/healthcare-reviewer.mdnew file mode 100644index 000000000..94e84bcf1--- /dev/null+++ b/agents/healthcare-reviewer.md@@ -0,0 +1,83 @@+---+name: healthcare-reviewer+description: Reviews healthcare application code for clinical safety, CDSS accuracy, PHI compliance, and medical data integrity. Specialized for EMR/EHR, clinical decision support, and health information systems.+tools: ["Read", "Grep", "Glob"]+model: opus+---++# Healthcare Reviewer — Clinical Safety & PHI Compliance++You are a clinical informatics reviewer for healthcare software. Patient safety is your top priority. You review code for clinical accuracy, data protection, and regulatory compliance.++## Your Responsibilities++1. **CDSS accuracy** — Verify drug interaction logic, dose validation rules, and clinical scoring implementations match published medical standards+2. **PHI/PII protection** — Scan for patient data exposure in logs, errors, responses, URLs, and client storage+3. **Clinical data integrity** — Ensure audit trails, locked records, and cascade protection+4. **Medical data correctness** — Verify ICD-10/SNOMED mappings, lab reference ranges, and drug database entries+5. **Integration compliance** — Validate HL7/FHIR message handling and error recovery++## Critical Checks++### CDSS Engine++- [ ] All drug interaction pairs produce correct alerts (both directions)+- [ ] Dose validation rules fire on out-of-range values+- [ ] Clinical scoring matches published specification (NEWS2 = Royal College of Physicians, qSOFA = Sepsis-3)+- [ ] No false negatives (missed interaction = patient safety event)+- [ ] Malformed inputs produce errors, NOT silent passes++### PHI Protection++- [ ] No patient data in `console.log`, `console.error`, or error messages+- [ ] No PHI in URL parameters or query strings+- [ ] No PHI in browser localStorage/sessionStorage+- [ ] No `service_role` key in client-side code+- [ ] RLS enabled on all tables with patient data+- [ ] Cross-facility data isolation verified++### Clinical Workflow++- [ ] Encounter lock prevents edits (addendum only)+- [ ] Audit trail entry on every create/read/update/delete of clinical data+- [ ] Critical alerts are non-dismissable (not toast notifications)+- [ ] Override reasons logged when clinician proceeds past critical alert+- [ ] Red flag symptoms trigger visible alerts++### Data Integrity++- [ ] No CASCADE DELETE on patient records+- [ ] Concurrent edit detection (optimistic locking or conflict resolution)+- [ ] No orphaned records across clinical tables+- [ ] Timestamps use consistent timezone++## Output Format++```+## Healthcare Review: [module/feature]++### Patient Safety Impact: [CRITICAL / HIGH / MEDIUM / LOW / NONE]++### Clinical Accuracy+- CDSS: [checks passed/failed]+- Drug DB: [verified/issues]+- Scoring: [matches spec/deviates]++### PHI Compliance+- Exposure vectors checked: [list]+- Issues found: [list or none]++### Issues+1. [PATIENT SAFETY / CLINICAL / PHI / TECHNICAL] Description+ - Impact: [potential harm or exposure]+ - Fix: [required change]++### Verdict: [SAFE TO DEPLOY / NEEDS FIXES / BLOCK — PATIENT SAFETY RISK]+```++## Rules++- When in doubt about clinical accuracy, flag as NEEDS REVIEW — never approve uncertain clinical logic+- A single missed drug interaction is worse than a hundred false alarms+- PHI exposure is always CRITICAL severity, regardless of how small the leak+- Never approve code that silently catches CDSS errorsdiff --git a/skills/healthcare-cdss-patterns/SKILL.md b/skills/healthcare-cdss-patterns/SKILL.mdnew file mode 100644index 000000000..00863466e--- /dev/null+++ b/skills/healthcare-cdss-patterns/SKILL.md@@ -0,0 +1,239 @@+---+name: healthcare-cdss-patterns+description: Clinical Decision Support System (CDSS) development patterns. Drug interaction checking, dose validation, clinical scoring (NEWS2, qSOFA), alert severity classification, and integration into EMR workflows.+origin: Health1 Super Speciality Hospitals — contributed by Dr. Keyur Patel+version: "1.0.0"+observe: "PostToolUse"+feedback: "manual"+rollback: "git revert"+---++# Healthcare CDSS Development Patterns++Patterns for building Clinical Decision Support Systems that integrate into EMR workflows. CDSS modules are patient safety critical — zero tolerance for false negatives.++## When to Activate++- Implementing drug interaction checking+- Building dose validation engines+- Implementing clinical scoring systems (NEWS2, qSOFA, APACHE, GCS)+- Designing alert systems for abnormal clinical values+- Building medication order entry with safety checks+- Integrating lab result interpretation with clinical context++## Architecture++```+EMR UI+ ↓ (user enters data)+CDSS Engine (pure functions, no side effects)+ ├── Drug Interaction Checker+ ├── Dose Validator+ ├── Clinical Scoring (NEWS2, qSOFA, etc.)+ └── Alert Classifier+ ↓ (returns alerts)+EMR UI (displays alerts inline, blocks if critical)+```++**Key principle:** The CDSS engine should be a pure function library with zero side effects. Input clinical data, output alerts. This makes it fully testable.++## Drug Interaction Checking++### Data Model++```typescript+interface DrugInteractionPair {+ drugA: string; // generic name+ drugB: string; // generic name+ severity: 'critical' | 'major' | 'minor';+ mechanism: string; // e.g., "CYP3A4 inhibition"+ clinicalEffect: string; // e.g., "Increased bleeding risk"+ recommendation: string; // e.g., "Avoid combination" or "Monitor INR closely"+}++interface InteractionAlert {+ severity: 'critical' | 'major' | 'minor';+ pair: [string, string];+ message: string;+ recommendation: string;+}+```++### Implementation Pattern++```typescript+function checkInteractions(+ newDrug: string,+ currentMedications: string[],+ allergyList: string[]+): InteractionAlert[] {+ const alerts: InteractionAlert[] = [];++ // Check drug-drug interactions+ for (const current of currentMedications) {+ const interaction = findInteraction(newDrug, current);+ if (interaction) {+ alerts.push({+ severity: interaction.severity,+ pair: [newDrug, current],+ message: interaction.clinicalEffect,+ recommendation: interaction.recommendation+ });+ }+ }++ // Check drug-allergy interactions+ for (const allergy of allergyList) {+ if (isCrossReactive(newDrug, allergy)) {+ alerts.push({+ severity: 'critical',+ pair: [newDrug, allergy],+ message: `Cross-reactivity with documented allergy: ${allergy}`,+ recommendation: 'Do not prescribe without allergy consultation'+ });+ }+ }++ // Sort by severity (critical first)+ return alerts.sort((a, b) =>+ severityOrder(a.severity) - severityOrder(b.severity)+ );+}+```++### Interaction pairs must be bidirectional++If Drug A interacts with Drug B, then Drug B interacts with Drug A. Store once, check both directions.++## Dose Validation++```typescript+interface DoseValidationResult {+ valid: boolean;+ message: string;+ suggestedRange: { min: number; max: number; unit: string };+ factors: string[]; // what was considered (weight, age, renal function)+}++function validateDose(+ drug: string,+ dose: number,+ route: 'oral' | 'iv' | 'im' | 'sc' | 'topical',+ patientWeight?: number,+ patientAge?: number,+ renalFunction?: number // eGFR+): DoseValidationResult {+ const rules = getDoseRules(drug, route);+ if (!rules) return { valid: true, message: 'No validation rules available', suggestedRange: null, factors: [] };++ // Weight-based dosing+ if (rules.weightBased && patientWeight) {+ const maxDose = rules.maxPerKg * patientWeight;+ if (dose > maxDose) {+ return {+ valid: false,+ message: `Dose ${dose}${rules.unit} exceeds max ${maxDose}${rules.unit} for ${patientWeight}kg patient`,+ suggestedRange: { min: rules.minPerKg * patientWeight, max: maxDose, unit: rules.unit },+ factors: ['weight']+ };+ }+ }++ // Absolute max dose+ if (dose > rules.absoluteMax) {+ return {+ valid: false,+ message: `Dose ${dose}${rules.unit} exceeds absolute max ${rules.absoluteMax}${rules.unit}`,+ suggestedRange: { min: rules.typicalMin, max: rules.absoluteMax, unit: rules.unit },+ factors: ['absolute_max']+ };+ }++ return { valid: true, message: 'Within range', suggestedRange: { min: rules.typicalMin, max: rules.typicalMax, unit: rules.unit }, factors: [] };+}+```++## Clinical Scoring: NEWS2++National Early Warning Score 2 — standardized assessment of acute illness severity:++```typescript+interface NEWS2Input {+ respiratoryRate: number;+ oxygenSaturation: number;+ supplementalOxygen: boolean;+ temperature: number;+ systolicBP: number;+ heartRate: number;+ consciousness: 'alert' | 'voice' | 'pain' | 'unresponsive';+}++interface NEWS2Result {+ total: number; // 0-20+ risk: 'low' | 'low-medium' | 'medium' | 'high';+ components: Record<string, number>;+ escalation: string; // recommended clinical action+}+```++Scoring tables must match the Royal College of Physicians NEWS2 specification exactly. Any deviation is a patient safety issue.++## Alert Severity and UI Behavior++| Severity | UI Behavior | Clinician Action Required |+|----------|-------------|--------------------------|+| Critical | Block action. Non-dismissable modal. Red. | Must document override reason to proceed |+| Major | Warning banner inline. Orange. | Must acknowledge before proceeding |+| Minor | Info note inline. Yellow. | Awareness only, no action required |++**Rules:**+- Critical alerts must NEVER be auto-dismissed+- Critical alerts must NEVER be toast notifications+- Override reasons must be stored in the audit trail+- Alert fatigue is real — only use critical for genuinely dangerous situations++## Testing CDSS (Zero Tolerance for False Negatives)++```typescript+describe('CDSS — Patient Safety', () => {+ // Every known interaction pair MUST fire+ INTERACTION_PAIRS.forEach(({ drugA, drugB, severity }) => {+ it(`detects ${drugA} + ${drugB} (${severity})`, () => {+ const alerts = checkInteractions(drugA, [drugB], []);+ expect(alerts.length).toBeGreaterThan(0);+ expect(alerts[0].severity).toBe(severity);+ });++ // Bidirectional check+ it(`detects ${drugB} + ${drugA} (reverse)`, () => {+ const alerts = checkInteractions(drugB, [drugA], []);+ expect(alerts.length).toBeGreaterThan(0);+ });+ });++ // Dose validation+ DOSE_RULES.forEach((rule) => {+ it(`validates ${rule.drug}: ${rule.scenario}`, () => {+ const result = validateDose(rule.drug, rule.dose, rule.route, rule.weight, rule.age);+ expect(result.valid).toBe(rule.expectedValid);+ });+ });++ // No silent failures+ it('handles malformed drug data gracefully', () => {+ expect(() => checkInteractions('', [], [])).not.toThrow();+ expect(() => checkInteractions(null as any, [], [])).not.toThrow();+ });+});+```++**Pass criteria: 100%.** A single missed interaction is a patient safety event.++## Anti-Patterns++- ❌ Making CDSS checks optional or skippable without documented reason+- ❌ Implementing interaction checks as toast notifications+- ❌ Using `any` types for drug or clinical data+- ❌ Hardcoding interaction pairs instead of using a maintainable data structure+- ❌ Testing with mocked data only (must test with real drug names)+- ❌ Silently catching errors in CDSS engine (must surface failures loudly)diff --git a/skills/healthcare-emr-patterns/SKILL.md b/skills/healthcare-emr-patterns/SKILL.mdnew file mode 100644index 000000000..a9cc79df4--- /dev/null+++ b/skills/healthcare-emr-patterns/SKILL.md@@ -0,0 +1,139 @@+---+name: healthcare-emr-patterns+description: EMR/EHR development patterns for healthcare applications. Clinical safety, encounter workflows, prescription generation, clinical decision support integration, and accessibility-first UI for medical data entry.+origin: Health1 Super Speciality Hospitals — contributed by Dr. Keyur Patel+version: "1.0.0"+observe: "PostToolUse"+feedback: "manual"+rollback: "git revert"+---++# Healthcare EMR Development Patterns++Patterns for building Electronic Medical Record (EMR) and Electronic Health Record (EHR) systems. Prioritizes patient safety, clinical accuracy, and practitioner efficiency.++## When to Activate++- Building patient encounter workflows (complaint → exam → diagnosis → prescription)+- Implementing clinical note-taking (structured + free text + voice-to-text)+- Designing prescription/medication modules with drug interaction checking+- Integrating Clinical Decision Support Systems (CDSS)+- Building lab result displays with reference range highlighting+- Implementing audit trails for clinical data+- Designing healthcare-accessible UIs for clinical data entry++## Core Principles++### 1. Patient Safety First++Every design decision must be evaluated against: "Could this harm a patient?"++- Drug interactions MUST alert, not silently pass+- Abnormal lab values MUST be visually flagged+- Critical vitals MUST trigger escalation workflows+- No clinical data modification without audit trail++### 2. Single-Page Encounter Flow++Clinical encounters should flow vertically on a single page — no tab switching during patient interaction:++```+Patient Header (sticky — always visible)+├── Demographics, allergies, active medications+│+Encounter Flow (vertical scroll)+├── 1. Chief Complaint (structured templates + free text)+├── 2. History of Present Illness+├── 3. Physical Examination (system-wise)+├── 4. Vitals (auto-trigger clinical scoring)+├── 5. Diagnosis (ICD-10/SNOMED search)+├── 6. Medications (drug DB + interaction check)+├── 7. Investigations (lab/radiology orders)+├── 8. Plan & Follow-up+└── 9. Sign / Lock / Print+```++### 3. Smart Template System++Build templates for common presentations:++```typescript+interface ClinicalTemplate {+ id: string;+ name: string; // e.g., "Chest Pain"+ chips: string[]; // clickable symptom chips+ requiredFields: string[]; // mandatory data points+ redFlags: string[]; // triggers non-dismissable alert+ icdSuggestions: string[]; // pre-mapped diagnosis codes+}+```++**Red flags** in any template must trigger a visible, non-dismissable alert — NOT a toast notification.++### 4. Medication Safety Pattern++```+User selects drug+ → Check current medications for interactions+ → Check encounter medications for interactions+ → Check patient allergies+ → Validate dose against weight/age/renal function+ → Display alerts (critical = block, major = require override reason)+ → Log override reason if clinician proceeds+```++Critical interactions should **block prescribing by default**. The clinician must explicitly override with a documented reason.++### 5. Locked Encounter Pattern++Once a clinical encounter is signed:+- No edits allowed — only addendum+- Addendum is a new record linked to the original+- Both original and addendum appear in the patient timeline+- Audit trail captures who signed, when, and any addenda++## UI Patterns for Clinical Data++### Vitals Display++- Current values with normal range highlighting (green/yellow/red)+- Trend arrows comparing to previous measurement+- Clinical scoring auto-calculated (NEWS2, qSOFA, MEWS)+- Scoring result displayed inline with escalation guidance++### Lab Results Display++- Normal range highlighting with institution-specific ranges+- Previous value comparison (trend)+- Critical values flagged with non-dismissable alert+- Timestamp of collection and analysis+- Pending orders shown with expected turnaround++### Prescription PDF++- One-click generation+- Patient demographics, allergies, diagnosis+- Drug name (generic + brand), dose, route, frequency, duration+- Clinician signature block+- QR code linking to digital record (optional)++## Accessibility for Healthcare++Healthcare UIs have stricter accessibility requirements than typical web apps:++- **4.5:1 minimum contrast** (WCAG AA) — clinicians work in varied lighting+- **Large touch targets** (44x44px minimum) — for gloved/rushed interaction+- **Keyboard navigation** — for power users entering data rapidly+- **No color-only indicators** — always pair color with text/icon (colorblind clinicians)+- **Screen reader labels** on all form fields — for voice-assisted data entry+- **No auto-dismissing toasts** for clinical alerts — clinician must actively acknowledge++## Anti-Patterns++- ❌ Storing clinical data in browser localStorage+- ❌ Silent failures in drug interaction checking+- ❌ Dismissable toasts for critical clinical alerts+- ❌ Tab-based encounter UIs that fragment the clinical workflow+- ❌ Allowing edits to signed/locked encounters+- ❌ Displaying clinical data without audit trail+- ❌ Using `any` type for clinical data structuresdiff --git a/skills/healthcare-eval-harness/SKILL.md b/skills/healthcare-eval-harness/SKILL.mdnew file mode 100644index 000000000..e65cd23d2--- /dev/null+++ b/skills/healthcare-eval-harness/SKILL.md@@ -0,0 +1,169 @@+---+name: healthcare-eval-harness+description: Patient safety evaluation harness for healthcare application deployments. Automated test suites for CDSS accuracy, PHI exposure, clinical workflow integrity, and integration compliance. Blocks deployments on safety failures.+origin: Health1 Super Speciality Hospitals — contributed by Dr. Keyur Patel+version: "1.0.0"+observe: "PostToolUse"+feedback: "manual"+rollback: "git revert"+---++# Healthcare Eval Harness — Patient Safety Verification++Automated verification system for healthcare application deployments. A single CRITICAL failure blocks deployment. Patient safety is non-negotiable.++## When to Activate++- Before any deployment of EMR/EHR applications+- After modifying CDSS logic (drug interactions, dose validation, scoring)+- After changing database schemas that touch patient data+- After modifying authentication or access control+- During CI/CD pipeline configuration for healthcare apps+- After resolving merge conflicts in clinical modules++## Eval Categories++### 1. CDSS Accuracy (CRITICAL — 100% required)++Tests all clinical decision support logic:++- Drug interaction pairs: every known pair must fire an alert+- Dose validation: out-of-range doses must be flagged+- Clinical scoring: results must match published specifications+- No false negatives: a missed alert is a patient safety event+- No silent failures: malformed input must error, not silently pass++```bash+npx jest --testPathPattern='tests/cdss' --bail --ci+```++### 2. PHI Exposure (CRITICAL — 100% required)++Tests for protected health information leaks:++- API error responses contain no PHI+- Console output contains no patient data+- URL parameters contain no PHI+- Browser storage contains no PHI+- Cross-facility data isolation works (multi-tenant)+- Unauthenticated requests return zero patient rows+- Service role keys absent from client bundles++```bash+npx jest --testPathPattern='tests/security/phi' --bail --ci+```++### 3. Data Integrity (CRITICAL — 100% required)++Tests for clinical data safety:++- Locked encounters cannot be modified+- Audit trail entries exist for every write operation+- Cascade deletes are blocked on patient records+- Concurrent edits trigger conflict resolution+- No orphaned records across related tables++```bash+npx jest --testPathPattern='tests/data-integrity' --bail --ci+```++### 4. Clinical Workflow (HIGH — 95%+ required)++Tests end-to-end clinical workflows:++- Complete encounter flow (complaint → exam → diagnosis → Rx → lock)+- Template rendering and submission for all clinical templates+- Medication set population and interaction checking+- Drug/diagnosis search functionality+- Prescription PDF generation+- Red flag alert triggering++```bash+npx jest --testPathPattern='tests/clinical' --ci+```++### 5. Integration Compliance (HIGH — 95%+ required)++Tests external system integrations:++- HL7 message parsing (v2.x)+- FHIR resource validation (if applicable)+- Lab result mapping to correct patients+- Malformed message handling (no crashes)++```bash+npx jest --testPathPattern='tests/integration' --ci+```++## CI/CD Integration++### GitHub Actions Example++```yaml+name: Healthcare Safety Gate+on: [push, pull_request]++jobs:+ safety-gate:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ - run: npm ci++ # CRITICAL gates — must pass 100%+ - name: CDSS Accuracy+ run: npx jest --testPathPattern='tests/cdss' --bail --ci++ - name: PHI Exposure Check+ run: npx jest --testPathPattern='tests/security/phi' --bail --ci++ - name: Data Integrity+ run: npx jest --testPathPattern='tests/data-integrity' --bail --ci++ # HIGH gates — must pass 95%++ - name: Clinical Workflows+ run: npx jest --testPathPattern='tests/clinical' --ci++ - name: Integration Compliance+ run: npx jest --testPathPattern='tests/integration' --ci+```++## Pass/Fail Matrix++| Category | Threshold | On Failure |+|----------|-----------|------------|+| CDSS Accuracy | 100% | **BLOCK deployment** |+| PHI Exposure | 100% | **BLOCK deployment** |+| Data Integrity | 100% | **BLOCK deployment** |+| Clinical Workflow | 95%+ | WARN, allow with review |+| Integration | 95%+ | WARN, allow with review |++## Eval Report Format++```+## Healthcare Eval: [date] [commit]++### Patient Safety: PASS / FAIL++| Category | Tests | Pass | Fail | Status |+|----------|-------|------|------|--------|+| CDSS Accuracy | N | N | 0 | PASS |+| PHI Exposure | N | N | 0 | PASS |+| Data Integrity | N | N | 0 | PASS |+| Clinical Workflow | N | N | N | 95%+ |+| Integration | N | N | N | 95%+ |++### Coverage: X% (target: 80%+)+### Verdict: SAFE TO DEPLOY / BLOCKED+```++## Anti-Patterns++- ❌ Skipping CDSS tests "because they passed last time"+- ❌ Setting CRITICAL thresholds below 100%+- ❌ Using `--no-bail` on CRITICAL test suites+- ❌ Mocking the CDSS engine in integration tests (must test real logic)+- ❌ Allowing deployments when safety gate is reddiff --git a/skills/healthcare-phi-compliance/SKILL.md b/skills/healthcare-phi-compliance/SKILL.mdnew file mode 100644index 000000000..b84de1c65--- /dev/null+++ b/skills/healthcare-phi-compliance/SKILL.md@@ -0,0 +1,185 @@+---+name: healthcare-phi-compliance+description: Protected Health Information (PHI) and Personally Identifiable Information (PII) compliance patterns for healthcare applications. Covers data classification, access control, audit trails, encryption, and common leak vectors.+origin: Health1 Super Speciality Hospitals — contributed by Dr. Keyur Patel+version: "1.0.0"+observe: "PostToolUse"+feedback: "manual"+rollback: "git revert"+---++# Healthcare PHI/PII Compliance Patterns++Patterns for protecting patient data, clinician data, and financial data in healthcare applications. Applicable to HIPAA (US), DISHA (India), GDPR (EU), and general healthcare data protection.++## When to Activate++- Building any feature that touches patient records+- Implementing access control or authentication for clinical systems+- Designing database schemas for healthcare data+- Building APIs that return patient or clinician data+- Implementing audit trails or logging+- Reviewing code for data exposure vulnerabilities+- Setting up Row-Level Security (RLS) for multi-tenant healthcare systems++## Data Classification++### PHI (Protected Health Information)++Any data that can identify a patient AND relates to their health:++- Patient name, date of birth, address, phone, email+- National ID numbers (SSN, Aadhaar, NHS number)+- Medical record numbers+- Diagnoses, medications, lab results, imaging+- Insurance policy and claim details+- Appointment and admission records+- Any combination of the above++### PII (Personally Identifiable Information)++Non-patient sensitive data in healthcare systems:++- Clinician/staff personal details+- Doctor fee structures and payout amounts+- Employee salary and bank details+- Vendor payment information++## Access Control Patterns++### Row-Level Security (Supabase/PostgreSQL)++```sql+-- Enable RLS on every PHI table+ALTER TABLE patients ENABLE ROW LEVEL SECURITY;++-- Scope access by facility/centre+CREATE POLICY "staff_read_own_facility"+ ON patients FOR SELECT+ TO authenticated+ USING (+ facility_id IN (+ SELECT facility_id FROM staff_assignments+ WHERE user_id = auth.uid()+ AND role IN ('doctor', 'nurse', 'lab_tech', 'admin')+ )+ );++-- Audit log: insert-only (no updates, no deletes)+CREATE POLICY "audit_insert_only"+ ON audit_log FOR INSERT+ TO authenticated+ WITH CHECK (user_id = auth.uid());++CREATE POLICY "audit_no_modify" ON audit_log FOR UPDATE USING (false);+CREATE POLICY "audit_no_delete" ON audit_log FOR DELETE USING (false);+```++### API Authentication++- Every API route handling PHI MUST require authentication+- Use short-lived tokens (JWT with 15-min expiry for clinical sessions)+- Implement session timeout (auto-logout after inactivity)+- Log every PHI access with user ID, timestamp, and resource accessed++## Common Leak Vectors (Check Every Deployment)++### 1. Error Messages++```typescript+// ❌ BAD — leaks PHI in error+throw new Error(`Patient ${patient.name} not found in ${patient.facility}`);++// ✅ GOOD — generic error, log details server-side+logger.error('Patient lookup failed', { patientId, facilityId });+throw new Error('Record not found');+```++### 2. Console Output++```typescript+// ❌ BAD+console.log('Processing patient:', patient);++// ✅ GOOD+console.log('Processing patient:', patient.id); // ID only+```++### 3. URL Parameters++```+❌ /patients?name=John+Doe&dob=1990-01-01+✅ /patients/uuid-here (lookup by opaque ID)+```++### 4. Browser Storage++```typescript+// ❌ NEVER store PHI in localStorage/sessionStorage+localStorage.setItem('currentPatient', JSON.stringify(patient));++// ✅ Keep PHI in memory only, fetch on demand+const [patient, setPatient] = useState<Patient | null>(null);+```++### 5. Service Role Keys++```typescript+// ❌ NEVER use service_role key in client-side code+const supabase = createClient(url, SUPABASE_SERVICE_ROLE_KEY);++// ✅ ALWAYS use anon key — let RLS enforce access+const supabase = createClient(url, SUPABASE_ANON_KEY);+```++### 6. Logs and Monitoring++- Never log full patient records+- Log patient IDs, not names+- Sanitize stack traces before sending to error tracking services+- Ensure log storage itself is access-controlled++## Audit Trail Requirements++Every PHI access or modification must be logged:++```typescript+interface AuditEntry {+ timestamp: string;+ user_id: string;+ patient_id: string;+ action: 'create' | 'read' | 'update' | 'delete' | 'print' | 'export';+ resource_type: string;+ resource_id: string;+ changes?: { before: object; after: object }; // for updates+ ip_address: string;+ session_id: string;+}+```++## Database Schema Tagging++Mark PHI/PII columns at the schema level so automated tools can identify them:++```sql+COMMENT ON COLUMN patients.name IS 'PHI: patient_name';+COMMENT ON COLUMN patients.dob IS 'PHI: date_of_birth';+COMMENT ON COLUMN patients.aadhaar IS 'PHI: national_id';+COMMENT ON COLUMN doctor_payouts.amount IS 'PII: financial';+COMMENT ON COLUMN employees.salary IS 'PII: financial';+```++## Deployment Checklist++Before every deployment of a healthcare application:++- [ ] No PHI in error messages or stack traces+- [ ] No PHI in console.log/console.error+- [ ] No PHI in URL parameters+- [ ] No PHI in browser storage+- [ ] No service_role key in client code+- [ ] RLS enabled on all PHI/PII tables+- [ ] Audit trail for all data modifications+- [ ] Session timeout configured+- [ ] API authentication on all PHI endpoints+- [ ] Cross-facility data isolation verified