EHR Quality Governance
Overview
This skill covers EHR quality-governance tasks against a read-only FHIR-like
REST API. Every task has the same core shape: fetch records from the API,
apply clinical reconciliation and validation rules, and return a single
normalized JSON object that conforms to a provided answer template. Never
include explanatory prose, markdown fences, or commentary outside that JSON
object.
API Reference
The base URL is supplied as <TASK_ENV_BASE_URL> in the prompt. Replace that
placeholder with the real URL from environment_access.md before making any
requests. All endpoints are GET only.
| Endpoint |
Returns |
/api/patients |
Patient list/search |
/api/patients/{id} |
Demographics: name, DOB, MRN, sex, address, phone, insurance_id, primary_care_provider_id |
/api/patients/{id}/conditions |
Condition list: code, description, normalized_key, status, source |
/api/patients/{id}/medications |
Medication list: name, dose, route, frequency, normalized_key, status |
/api/patients/{id}/allergies |
Allergy list: allergen, reaction, severity, normalized_key, status |
/api/patients/{id}/encounters |
Encounters: date, type, signed_status, provider_id, diagnosis_codes, medications_mentioned |
/api/patients/{id}/immunizations |
Immunizations: vaccine, date, immunization_id |
/api/patients/{id}/documents |
Documents: type, date, status, document_id |
/api/patients/{id}/service-requests |
Service requests for the patient |
/api/patients/{id}/disclosures |
Disclosures: purpose, status, date, recipient_provider_id |
/api/audit-logs |
Audit log entries |
/api/duplicates/candidates |
Duplicate candidate listing |
/api/duplicates/{candidate_id} |
Candidate detail: status, patient_ids, match/conflict signals |
/api/referrals |
Referral search/list |
/api/referrals/{referral_id} |
Referral detail: patient, diagnosis_code, diagnosis_narrative, service_line, authorization, status, urgency, batch_id |
/api/icd10 |
ICD-10 code directory |
/api/icd10/{code} |
Code detail: chapter, description, laterality, terms |
/api/providers |
Provider search |
/api/providers/{provider_id} |
Provider detail: name, role, service_line, facility, phone, fax |
/api/service-codes |
Service code listing |
/api/service-codes/{code} |
Service code detail |
API Interaction Rules
- Use GET for every request. Parallelize independent fetches in a single
tool-call batch (e.g., fetch conditions for two patients at once).
- Validate that every response is JSON before using it.
- A 404 means the resource does not exist — do not retry or invent data.
Answer Template Protocol
Every task supplies an answer template at input/payloads/answer_template.json.
Follow these rules without exception.
Strict Conformance
- Return exactly one JSON object with every required top-level key.
- Use the exact key names, enum values, and types declared in the template.
Do not invent extra keys or variant enum strings.
- If the template says a field is
"string", emit a string (or null when
null is allowed). If it says "integer", emit an integer. If it says
"boolean", emit true or false.
- The final output is the JSON object itself — no surrounding text.
Array Sorting
Unless the template explicitly overrides sorting for a specific field:
- String arrays (set semantics): sort alphabetically ascending.
- Patient IDs, document IDs, audit IDs: sort alphabetically ascending.
- Object arrays with a declared key ordering (e.g., "sort by referral_id
ascending"): follow that rule.
- Encounter arrays ordered by date: newest to oldest.
- When uncertain, default to alphabetical ascending.
Normalized Keys
Clinical records carry a normalized_key — a machine-friendly canonical
identifier such as hypertension, right_knee_oa, metformin, penicillin.
- Extract
normalized_key values, not codes or display descriptions.
- Include only records with
status: "active" in active lists, unless
the template explicitly says otherwise.
- Exclude
inactive, resolved, and entered-in-error records from
active-key lists.
- Sort keys alphabetically ascending.
Clinical Reconciliation
Active List Union (Merge Packets)
When merging two patients:
- Fetch conditions, medications, and allergies from each patient's
dedicated endpoints (filter for active status).
- Collect all
normalized_key values across both patients into a set
(deduplicate — each key appears once).
- Sort alphabetically.
- Cross-check against the duplicate candidate's preview lists. If an
active key appears in a patient endpoint but is absent from the
duplicate preview, report it in a reconciliation field such as
keys_added_from_active_endpoints.
Condition Relevance
A condition is "referral-relevant" when its code matches the referral's
primary or supporting diagnosis codes, or when its clinical domain aligns
with the referral's service line. Conditions unrelated to the referral
reason should be marked referral_relevant: false.
Medication Relevance for Referrals
Map medication highlights to the referral's clinical context. Common
patterns and their highlight reasons include:
- Diuretics (furosemide) for heart failure →
heart_failure_diuretic
- ACE inhibitors (lisinopril) for hypertension →
blood_pressure_management
- Insulin/metformin for diabetes →
diabetes_management
- Statins for hyperlipidemia →
lipid_management
- Other active medications →
other_active_medication
Use the exact highlight_reason enum values from the template.
Identity and Duplicate Analysis
Match Signals
Conditions that suggest two patients are the same person:
same_dob — identical date of birth
same_insurance — identical insurance ID
same_phone — identical phone number
same_given_name — name matches exactly or is a recognized variant (e.g., Bob/Robert)
similar_address — addresses match within minor formatting differences
shared_external_*_document — an external document references both records
name_variant — names are recognizably the same person
Conflict Signals
Conditions that suggest two patients are different people:
different_given_name — names differ substantively
different_dob — dates of birth differ
different_phone — phone numbers differ
different_insurance — insurance IDs differ
different_address — addresses differ substantively
opposite_laterality_problem — one patient has a left-side condition while the other has a right-side condition of the same type
Demographic Comparison
Compare these fields individually between two patient records: sex,
insurance_id, phone, address, given_name, family_name, DOB,
primary_care_provider_id. Report each as a match (identical or trivially
variant) or a conflict (substantively different). Abbreviations and
missing secondary address elements are minor, not substantive.
Merge Target Selection
- Target (canonical record to keep): the patient with the richer
active clinical data, or the one the duplicate candidate identifies
as the primary. Usually the earlier-created record.
- Source (record to absorb): the duplicate or less-complete record.
- Prefer the duplicate candidate's own signal orientation when it
indicates which patient is the duplicate of which.
Merge Disposition
ready_to_merge / merge_ready: strong identity match, no blocking
conflicts, duplicate candidate confirms the relationship.
needs_review / merge_ready_with_conflict_review: mixed signals
with some conflicts that warrant human review.
do_not_merge / needs_manual_review: conflicts dominate or the
candidate status is not_duplicate.
ICD-10 Code Validation
Chapter Validation
Each ICD-10 code belongs to a chapter. For service-line-specific tasks:
- Orthopedics referrals: codes must be in "Musculoskeletal". Codes
in "Injury", "Respiratory", or any other chapter are
out_of_range_chapter.
- Cardiology referrals: codes should be in "Circulatory" or a closely
related chapter for symptoms tied to cardiac conditions.
- Codes absent from the ICD-10 directory are
unknown_code.
Laterality and Narrative Matching
ICD-10 codes encode laterality (M17.11 = right knee OA, M17.12 = left knee OA,
S83.241A = right medial meniscus tear, S83.242A = left medial meniscus tear).
Always verify against the ICD-10 directory entry, never from memory.
- Laterality mismatch: the code's side (left/right) contradicts the
referral narrative or patient evidence.
- Narrative mismatch: the code's official description does not match
the referral's diagnosis narrative text. Compare the ICD-10 entry's
description and associated terms against the referral narrative.
- Missing laterality: the referral narrative omits the side when the
code encodes it (e.g., narrative says "meniscus tear" for S83.242A,
which is specifically "left medial meniscus tear").
For each mismatch referral, populate expected_terms from the ICD-10
directory entry's description and terms fields.
Reason Code Validation (Service Requests)
For each reason code on a ServiceRequest:
- Look up the code in
/api/icd10/{code}.
valid: true if found, false if not found.
chapter: from the ICD-10 entry (null if not found).
matches_patient_evidence: true when the patient has an active
condition whose domain matches the code's clinical area.
Referral Batch Audit Patterns
Process
- Retrieve all referrals in the target batch.
- For each referral, look up its diagnosis code, patient, and provider.
- Classify every referral into zero or more issue categories.
- Build follow-up queues and tier-based action plans.
- Compute summary counts that match the emitted arrays.
Classification Categories
Invalid or out-of-range codes: the diagnosis code's ICD-10 chapter
does not match the expected chapter for the referral's service line.
For orthopedics the expected chapter is "Musculoskeletal". Record the
actual_chapter from the ICD-10 lookup and issue_type of either
out_of_range_chapter or unknown_code.
Laterality or narrative mismatches: the code does not match the
referral's narrative in laterality, description, or completeness.
Record each mismatch type in mismatch_types and include the
expected_terms from the ICD-10 directory.
Duplicate groups: same patient with multiple referrals for the same
clinical issue. Group them with type same_patient_resubmission and
recommend consolidate_under_original. Sort referral_ids within each
group ascending.
Insurance anomalies: different patients sharing the same insurance
ID. This may indicate a duplicate or a membership anomaly. Do not merge
based on insurance alone; recommend verify_insurance_membership_do_not_merge.
Follow-Up Queues
Build four queues, each as an array of referral IDs sorted ascending:
authorization_missing: no authorization record found.
authorization_pending: authorization is in a pending state.
records_request: missing required office-note documents.
imaging_follow_up: missing or pending imaging documents.
Action Plan Tiers
- Tier 1 (Immediate):
urgent_coding_or_duplicate_blocker. Urgent
referrals with code issues, or duplicate-blocker referrals.
- Tier 2 (Short-term):
routine_coding_auth_or_document_blocker.
Routine referrals with coding, authorization, or document issues.
- Tier 3 (Administrative):
administrative_document_completion.
Referrals that only need document follow-up.
Distribute owner_provider_id across the available providers in the
relevant service line. A single referral can appear in at most one tier.
When a referral qualifies for multiple tiers, assign the highest
priority tier.
Duplicate Tiering Policy
When duplicate groups exist in a batch, the policy
tier_all_duplicate_group_rows_as_duplicate_blockers means every
referral in the duplicate group is a Tier 1 blocker. List all
duplicate-group referral IDs in tier_1_duplicate_blocker_referral_ids.
Same-patient referrals that are separate clinical reviews (different
body parts, different clinical questions) go in
separate_same_patient_referral_ids and are not duplicates.
Summary Counts
Every count must match the length of its corresponding array. Include
validated_ready_no_follow_up_count for referrals that appear in none
of the classification or follow-up arrays. Verify the total referral
row count, unique patient count, urgent count, and routine count against
the raw batch data.
Encounter Selection for Handoff Packets
- Fetch all encounters for the patient.
- Filter to clinical encounters (
care_transition, office_visit, and
similar). Exclude purely administrative encounters.
- Select the N most recent by date (the template specifies N; 4 is common).
- Sort selected encounters newest to oldest.
- Track excluded encounters separately: list their IDs sorted ascending
in
excluded_encounter_ids.
- The
selection_basis field carries a code describing the rule applied
(e.g., orthopedic_surgical_handoff_window).
Immunization and Disclosure Selection
- Immunization: fetch all, select the single most recent by date.
Include its immunization_id, date, and vaccine name.
- Disclosure: fetch all, find the one matching the recipient provider
and the workflow purpose (e.g.,
surgical handoff for orthopedics).
Report its status as permitted, pending, denied, or expired.
A missing or non-permitted disclosure is a blocking issue.
Risk Flag Derivation
For care transition packets, derive risk flags from clinical evidence.
Each flag needs an evidence entry linking the specific condition_keys,
medication_keys, and encounter_ids that support it. Evidence arrays sort
ascending. The overall risk_flag_evidence array sorts by risk_flag
ascending. Evidence encounters may include both selected handoff
encounters and excluded encounters.
Common risk-flag derivation patterns:
| Risk Flag |
Evidence to look for |
cognitive_memory_loss |
Active condition with normalized_key memory_loss or similar cognitive condition |
fall_risk_note_required |
Orthopedic conditions (hip/knee OA) combined with pain medications; encounters documenting mobility or fall concerns |
hypertension |
Active condition hypertension |
insulin_dependent_diabetes |
Active condition diabetes_type_2 with active medication insulin_glargine (or similar insulin preparation) |
latex_allergy |
Active allergy with allergen latex |
perioperative_glucose_plan_needed |
Diabetes condition with insulin medication in a surgical handoff context |
Only emit a flag when there is affirmative evidence from the patient's
records. Do not emit flags that have no supporting clinical data.
Provider Lookups
Fetch /api/providers/{provider_id} for each provider the packet needs.
Extract: name, role, service_line, facility, phone, fax. For specialist
contact reasons, describe why this specific provider is relevant to the
workflow. Service lines imply roles:
cardiology → Cardiologist
orthopedics → Orthopedic Surgeon
primary_care → Primary Care
pulmonology → Pulmonologist
neurology → Neurologist
oncology → Oncologist
skilled_nursing → Skilled Nursing Facility
Document Evidence
When selecting documents for a packet:
- Fetch documents for each relevant patient.
- Prefer documents with status
final. Include preliminary only if
no final version exists. Exclude cancelled.
- Include only documents that support the specific workflow: identity or
external continuity documents for merge packets; echocardiograms and
office notes for cardiology referrals; surgical or handoff documents
for care transitions.
- Exclude
chart_summary documents from evidence arrays — they are
internal summaries, not external continuity evidence.
- Sort document IDs alphabetically.
Required Document Gaps
For referral coordination, check for these common required documents and
report any that are missing in missing_required_documents:
echocardiogram — for cardiology referrals
office_note — documenting the referral reason
authorization — the referral authorization
medication_list — for medication reconciliation
allergy_confirmation — for allergy readiness
Service Request Quality Signals
When a task involves a ServiceRequest:
- Fetch the SR by ID.
- Extract: status, intent, priority, service_code, requester_provider_id,
performer_provider_id, authored_on, occurrence_date, reason_codes.
- Validate the service_code against
/api/service-codes/{code}.
- Validate each reason_code against
/api/icd10/{code} (see Reason
Code Validation above).
- Confirm the performer's service_line matches the expected specialty.
SBAR Coverage
For tasks checking SBAR (Situation, Background, Assessment, Recommendation)
coverage: examine the service request or referral documentation for all
four sections. complete is true only when all four are present. List
any missing sections explicitly in missing_sections.
Audit Logs
For merge packets, look for audit entries that document duplicate
candidate lifecycle events, patient record merges, or identity reviews.
Sort audit IDs alphabetically in evidence arrays.
Exclusion of Distractors
The environment includes distractor records. Exclude these from output:
- Inactive clinical records: conditions, medications, or allergies
with status
inactive, resolved, or entered-in-error stay out of
active lists.
- Unrelated documents: generic chart summaries and documents for
unrelated patients or workflows.
- Stale encounters: encounters outside the relevant time window or
purely administrative encounters.
- Irrelevant audit logs: entries for unrelated operations.
When the template has an excluded_distractors section, populate it with
the specific keys or IDs that were reviewed and excluded.
Packet Readiness Assessment
Every packet concludes with a readiness assessment:
ready / ready_to_send: all required data is present, valid, and
permits the action. No blocking issues.
ready_with_risk_flags / ready_with_review_note: substantially
complete but with noted risks the recipient should see. Still safe
to send.
not_ready / blocked / hold_for_*: one or more blocking issues
prevent sending. Report the specific issue codes from the template's
allowed values.
A packet is ready only when all required entities exist, all required
documents are received in final status, authorizations are approved
(or not required), disclosures are permitted, and provider assignments
are resolved.
Overall Workflow
For any EHR quality-governance task, follow this sequence:
Read the answer template fully. Note every field, type, enum
constraint, and sorting rule.
Identify the task type from the prompt (merge packet, referral
coordination, care transition, duplicate review, or referral audit).
Fetch core entities in parallel where possible: patients, the
primary business object (duplicate candidate, referral, service
request), and relevant providers.
Fetch clinical data for every involved patient: conditions,
medications, allergies — filtered to active status.
Fetch supporting data as needed: encounters, documents,
immunizations, disclosures, audit logs, ICD-10 codes, service codes.
Validate and reconcile: check ICD-10 chapters against service
lines, compare laterality and narrative, cross-reference identity
signals with demographics, verify document statuses, confirm
authorization states, and validate provider service lines.
Build the output JSON field by field following the template
exactly. Apply sorting. Respect enum constraints. Exclude distractors.
Verify before returning: every required key is present, every
array that should be sorted is sorted, every enum matches the
allowed values, no explanatory text appears outside the JSON, and
every summary count matches its source array length.
Common Pitfalls
- Not filtering by status: always check for
status: "active" when
gathering active clinical lists; inactive records are distractors.
- Including chart summaries as evidence:
chart_summary documents are
internal — exclude them from packet evidence.
- Wrong laterality: verify every ICD-10 code's laterality against the
directory entry; do not guess from memory.
- Swapping target and source in merges: target is the canonical record
to preserve; source is the duplicate to absorb.
- Skipping duplicate-preview reconciliation: always cross-check the
duplicate candidate's preview lists against individual patient endpoints.
- Omitting duplicate rows from Tier 1: when duplicate-tiering policy says
to block all duplicate rows, both the original and resubmission must appear.
- Empty arrays vs. omitted keys: emit
[] for empty array fields; never
omit the key or use null.
- Inconsistent summary counts: every count must equal the length of the
corresponding array elsewhere in the output.
1---2name: ehr-quality-governance-53description: >4 Use this skill whenever the user asks you to prepare EHR quality-governance5 packets, merge-readiness assessments, referral coordination packets,6 care-transition summaries, duplicate-chart reviews, or referral batch audits7 against a FHIR-like read-only REST API. These tasks always involve fetching8 patient clinical data, reconciling active lists, validating ICD-10 codes,9 identifying identity signals, and building a single normalized JSON output10 that conforms strictly to a supplied answer template. Trigger this skill for11 any prompt that mentions duplicate-chart merge, referral coordination, care12 transition, quality governance, referral audit, or that references patients13 together with conditions, medications, allergies, encounters, documents,14 service-requests, duplicates, referrals, ICD-10, providers, or disclosures15 against a shared EHR API. Even if the user does not use the exact phrase16 "quality governance," trigger this skill when they describe a clinical-data17 reconciliation or packet-preparation workflow that fits these patterns.18metadata:19 source: https://skillmd.com/skills/prism-shadow/ehr-quality-governance-520---2122# EHR Quality Governance2324## Overview2526This skill covers EHR quality-governance tasks against a read-only FHIR-like27REST API. Every task has the same core shape: fetch records from the API,28apply clinical reconciliation and validation rules, and return a single29normalized JSON object that conforms to a provided answer template. Never30include explanatory prose, markdown fences, or commentary outside that JSON31object.3233## API Reference3435The base URL is supplied as `<TASK_ENV_BASE_URL>` in the prompt. Replace that36placeholder with the real URL from `environment_access.md` before making any37requests. All endpoints are GET only.3839| Endpoint | Returns |40|---|---|41| `/api/patients` | Patient list/search |42| `/api/patients/{id}` | Demographics: name, DOB, MRN, sex, address, phone, insurance_id, primary_care_provider_id |43| `/api/patients/{id}/conditions` | Condition list: code, description, normalized_key, status, source |44| `/api/patients/{id}/medications` | Medication list: name, dose, route, frequency, normalized_key, status |45| `/api/patients/{id}/allergies` | Allergy list: allergen, reaction, severity, normalized_key, status |46| `/api/patients/{id}/encounters` | Encounters: date, type, signed_status, provider_id, diagnosis_codes, medications_mentioned |47| `/api/patients/{id}/immunizations` | Immunizations: vaccine, date, immunization_id |48| `/api/patients/{id}/documents` | Documents: type, date, status, document_id |49| `/api/patients/{id}/service-requests` | Service requests for the patient |50| `/api/patients/{id}/disclosures` | Disclosures: purpose, status, date, recipient_provider_id |51| `/api/audit-logs` | Audit log entries |52| `/api/duplicates/candidates` | Duplicate candidate listing |53| `/api/duplicates/{candidate_id}` | Candidate detail: status, patient_ids, match/conflict signals |54| `/api/referrals` | Referral search/list |55| `/api/referrals/{referral_id}` | Referral detail: patient, diagnosis_code, diagnosis_narrative, service_line, authorization, status, urgency, batch_id |56| `/api/icd10` | ICD-10 code directory |57| `/api/icd10/{code}` | Code detail: chapter, description, laterality, terms |58| `/api/providers` | Provider search |59| `/api/providers/{provider_id}` | Provider detail: name, role, service_line, facility, phone, fax |60| `/api/service-codes` | Service code listing |61| `/api/service-codes/{code}` | Service code detail |6263### API Interaction Rules6465- Use GET for every request. Parallelize independent fetches in a single66 tool-call batch (e.g., fetch conditions for two patients at once).67- Validate that every response is JSON before using it.68- A 404 means the resource does not exist — do not retry or invent data.6970## Answer Template Protocol7172Every task supplies an answer template at `input/payloads/answer_template.json`.73Follow these rules without exception.7475### Strict Conformance7677- Return exactly one JSON object with every required top-level key.78- Use the exact key names, enum values, and types declared in the template.79 Do not invent extra keys or variant enum strings.80- If the template says a field is `"string"`, emit a string (or null when81 null is allowed). If it says `"integer"`, emit an integer. If it says82 `"boolean"`, emit `true` or `false`.83- The final output is the JSON object itself — no surrounding text.8485### Array Sorting8687Unless the template explicitly overrides sorting for a specific field:8889- String arrays (set semantics): sort alphabetically ascending.90- Patient IDs, document IDs, audit IDs: sort alphabetically ascending.91- Object arrays with a declared key ordering (e.g., "sort by referral_id92 ascending"): follow that rule.93- Encounter arrays ordered by date: newest to oldest.94- When uncertain, default to alphabetical ascending.9596### Normalized Keys9798Clinical records carry a `normalized_key` — a machine-friendly canonical99identifier such as `hypertension`, `right_knee_oa`, `metformin`, `penicillin`.100101- Extract `normalized_key` values, not codes or display descriptions.102- Include only records with `status: "active"` in active lists, unless103 the template explicitly says otherwise.104- Exclude `inactive`, `resolved`, and `entered-in-error` records from105 active-key lists.106- Sort keys alphabetically ascending.107108## Clinical Reconciliation109110### Active List Union (Merge Packets)111112When merging two patients:1131141. Fetch conditions, medications, and allergies from each patient's115 dedicated endpoints (filter for active status).1162. Collect all `normalized_key` values across both patients into a set117 (deduplicate — each key appears once).1183. Sort alphabetically.1194. Cross-check against the duplicate candidate's preview lists. If an120 active key appears in a patient endpoint but is absent from the121 duplicate preview, report it in a reconciliation field such as122 `keys_added_from_active_endpoints`.123124### Condition Relevance125126A condition is "referral-relevant" when its code matches the referral's127primary or supporting diagnosis codes, or when its clinical domain aligns128with the referral's service line. Conditions unrelated to the referral129reason should be marked `referral_relevant: false`.130131### Medication Relevance for Referrals132133Map medication highlights to the referral's clinical context. Common134patterns and their highlight reasons include:135136- Diuretics (furosemide) for heart failure → `heart_failure_diuretic`137- ACE inhibitors (lisinopril) for hypertension → `blood_pressure_management`138- Insulin/metformin for diabetes → `diabetes_management`139- Statins for hyperlipidemia → `lipid_management`140- Other active medications → `other_active_medication`141142Use the exact `highlight_reason` enum values from the template.143144## Identity and Duplicate Analysis145146### Match Signals147148Conditions that suggest two patients are the same person:149150- `same_dob` — identical date of birth151- `same_insurance` — identical insurance ID152- `same_phone` — identical phone number153- `same_given_name` — name matches exactly or is a recognized variant (e.g., Bob/Robert)154- `similar_address` — addresses match within minor formatting differences155- `shared_external_*_document` — an external document references both records156- `name_variant` — names are recognizably the same person157158### Conflict Signals159160Conditions that suggest two patients are different people:161162- `different_given_name` — names differ substantively163- `different_dob` — dates of birth differ164- `different_phone` — phone numbers differ165- `different_insurance` — insurance IDs differ166- `different_address` — addresses differ substantively167- `opposite_laterality_problem` — one patient has a left-side condition while the other has a right-side condition of the same type168169### Demographic Comparison170171Compare these fields individually between two patient records: sex,172insurance_id, phone, address, given_name, family_name, DOB,173primary_care_provider_id. Report each as a match (identical or trivially174variant) or a conflict (substantively different). Abbreviations and175missing secondary address elements are minor, not substantive.176177### Merge Target Selection178179- **Target** (canonical record to keep): the patient with the richer180 active clinical data, or the one the duplicate candidate identifies181 as the primary. Usually the earlier-created record.182- **Source** (record to absorb): the duplicate or less-complete record.183- Prefer the duplicate candidate's own signal orientation when it184 indicates which patient is the duplicate of which.185186### Merge Disposition187188- `ready_to_merge` / `merge_ready`: strong identity match, no blocking189 conflicts, duplicate candidate confirms the relationship.190- `needs_review` / `merge_ready_with_conflict_review`: mixed signals191 with some conflicts that warrant human review.192- `do_not_merge` / `needs_manual_review`: conflicts dominate or the193 candidate status is `not_duplicate`.194195## ICD-10 Code Validation196197### Chapter Validation198199Each ICD-10 code belongs to a chapter. For service-line-specific tasks:200201- **Orthopedics referrals**: codes must be in "Musculoskeletal". Codes202 in "Injury", "Respiratory", or any other chapter are `out_of_range_chapter`.203- **Cardiology referrals**: codes should be in "Circulatory" or a closely204 related chapter for symptoms tied to cardiac conditions.205- Codes absent from the ICD-10 directory are `unknown_code`.206207### Laterality and Narrative Matching208209ICD-10 codes encode laterality (M17.11 = right knee OA, M17.12 = left knee OA,210S83.241A = right medial meniscus tear, S83.242A = left medial meniscus tear).211Always verify against the ICD-10 directory entry, never from memory.212213- **Laterality mismatch**: the code's side (left/right) contradicts the214 referral narrative or patient evidence.215- **Narrative mismatch**: the code's official description does not match216 the referral's diagnosis narrative text. Compare the ICD-10 entry's217 description and associated terms against the referral narrative.218- **Missing laterality**: the referral narrative omits the side when the219 code encodes it (e.g., narrative says "meniscus tear" for S83.242A,220 which is specifically "left medial meniscus tear").221222For each mismatch referral, populate `expected_terms` from the ICD-10223directory entry's description and terms fields.224225### Reason Code Validation (Service Requests)226227For each reason code on a ServiceRequest:2281. Look up the code in `/api/icd10/{code}`.2292. `valid`: `true` if found, `false` if not found.2303. `chapter`: from the ICD-10 entry (null if not found).2314. `matches_patient_evidence`: `true` when the patient has an active232 condition whose domain matches the code's clinical area.233234## Referral Batch Audit Patterns235236### Process2372381. Retrieve all referrals in the target batch.2392. For each referral, look up its diagnosis code, patient, and provider.2403. Classify every referral into zero or more issue categories.2414. Build follow-up queues and tier-based action plans.2425. Compute summary counts that match the emitted arrays.243244### Classification Categories245246**Invalid or out-of-range codes**: the diagnosis code's ICD-10 chapter247does not match the expected chapter for the referral's service line.248For orthopedics the expected chapter is "Musculoskeletal". Record the249`actual_chapter` from the ICD-10 lookup and `issue_type` of either250`out_of_range_chapter` or `unknown_code`.251252**Laterality or narrative mismatches**: the code does not match the253referral's narrative in laterality, description, or completeness.254Record each mismatch type in `mismatch_types` and include the255`expected_terms` from the ICD-10 directory.256257**Duplicate groups**: same patient with multiple referrals for the same258clinical issue. Group them with type `same_patient_resubmission` and259recommend `consolidate_under_original`. Sort referral_ids within each260group ascending.261262**Insurance anomalies**: different patients sharing the same insurance263ID. This may indicate a duplicate or a membership anomaly. Do not merge264based on insurance alone; recommend `verify_insurance_membership_do_not_merge`.265266### Follow-Up Queues267268Build four queues, each as an array of referral IDs sorted ascending:269270- `authorization_missing`: no authorization record found.271- `authorization_pending`: authorization is in a pending state.272- `records_request`: missing required office-note documents.273- `imaging_follow_up`: missing or pending imaging documents.274275### Action Plan Tiers276277- **Tier 1 (Immediate)**: `urgent_coding_or_duplicate_blocker`. Urgent278 referrals with code issues, or duplicate-blocker referrals.279- **Tier 2 (Short-term)**: `routine_coding_auth_or_document_blocker`.280 Routine referrals with coding, authorization, or document issues.281- **Tier 3 (Administrative)**: `administrative_document_completion`.282 Referrals that only need document follow-up.283284Distribute `owner_provider_id` across the available providers in the285relevant service line. A single referral can appear in at most one tier.286When a referral qualifies for multiple tiers, assign the highest287priority tier.288289### Duplicate Tiering Policy290291When duplicate groups exist in a batch, the policy292`tier_all_duplicate_group_rows_as_duplicate_blockers` means every293referral in the duplicate group is a Tier 1 blocker. List all294duplicate-group referral IDs in `tier_1_duplicate_blocker_referral_ids`.295Same-patient referrals that are separate clinical reviews (different296body parts, different clinical questions) go in297`separate_same_patient_referral_ids` and are not duplicates.298299### Summary Counts300301Every count must match the length of its corresponding array. Include302`validated_ready_no_follow_up_count` for referrals that appear in none303of the classification or follow-up arrays. Verify the total referral304row count, unique patient count, urgent count, and routine count against305the raw batch data.306307## Encounter Selection for Handoff Packets3083091. Fetch all encounters for the patient.3102. Filter to clinical encounters (`care_transition`, `office_visit`, and311 similar). Exclude purely administrative encounters.3123. Select the N most recent by date (the template specifies N; 4 is common).3134. Sort selected encounters newest to oldest.3145. Track excluded encounters separately: list their IDs sorted ascending315 in `excluded_encounter_ids`.3166. The `selection_basis` field carries a code describing the rule applied317 (e.g., `orthopedic_surgical_handoff_window`).318319## Immunization and Disclosure Selection320321- **Immunization**: fetch all, select the single most recent by date.322 Include its immunization_id, date, and vaccine name.323- **Disclosure**: fetch all, find the one matching the recipient provider324 and the workflow purpose (e.g., `surgical handoff` for orthopedics).325 Report its status as `permitted`, `pending`, `denied`, or `expired`.326 A missing or non-permitted disclosure is a blocking issue.327328## Risk Flag Derivation329330For care transition packets, derive risk flags from clinical evidence.331Each flag needs an evidence entry linking the specific condition_keys,332medication_keys, and encounter_ids that support it. Evidence arrays sort333ascending. The overall `risk_flag_evidence` array sorts by `risk_flag`334ascending. Evidence encounters may include both selected handoff335encounters and excluded encounters.336337Common risk-flag derivation patterns:338339| Risk Flag | Evidence to look for |340|---|---|341| `cognitive_memory_loss` | Active condition with normalized_key `memory_loss` or similar cognitive condition |342| `fall_risk_note_required` | Orthopedic conditions (hip/knee OA) combined with pain medications; encounters documenting mobility or fall concerns |343| `hypertension` | Active condition `hypertension` |344| `insulin_dependent_diabetes` | Active condition `diabetes_type_2` with active medication `insulin_glargine` (or similar insulin preparation) |345| `latex_allergy` | Active allergy with allergen `latex` |346| `perioperative_glucose_plan_needed` | Diabetes condition with insulin medication in a surgical handoff context |347348Only emit a flag when there is affirmative evidence from the patient's349records. Do not emit flags that have no supporting clinical data.350351## Provider Lookups352353Fetch `/api/providers/{provider_id}` for each provider the packet needs.354Extract: name, role, service_line, facility, phone, fax. For specialist355contact reasons, describe why this specific provider is relevant to the356workflow. Service lines imply roles:357358- `cardiology` → Cardiologist359- `orthopedics` → Orthopedic Surgeon360- `primary_care` → Primary Care361- `pulmonology` → Pulmonologist362- `neurology` → Neurologist363- `oncology` → Oncologist364- `skilled_nursing` → Skilled Nursing Facility365366## Document Evidence367368When selecting documents for a packet:369370- Fetch documents for each relevant patient.371- Prefer documents with status `final`. Include `preliminary` only if372 no final version exists. Exclude `cancelled`.373- Include only documents that support the specific workflow: identity or374 external continuity documents for merge packets; echocardiograms and375 office notes for cardiology referrals; surgical or handoff documents376 for care transitions.377- Exclude `chart_summary` documents from evidence arrays — they are378 internal summaries, not external continuity evidence.379- Sort document IDs alphabetically.380381### Required Document Gaps382383For referral coordination, check for these common required documents and384report any that are missing in `missing_required_documents`:385386- `echocardiogram` — for cardiology referrals387- `office_note` — documenting the referral reason388- `authorization` — the referral authorization389- `medication_list` — for medication reconciliation390- `allergy_confirmation` — for allergy readiness391392## Service Request Quality Signals393394When a task involves a ServiceRequest:3953961. Fetch the SR by ID.3972. Extract: status, intent, priority, service_code, requester_provider_id,398 performer_provider_id, authored_on, occurrence_date, reason_codes.3993. Validate the service_code against `/api/service-codes/{code}`.4004. Validate each reason_code against `/api/icd10/{code}` (see Reason401 Code Validation above).4025. Confirm the performer's service_line matches the expected specialty.403404## SBAR Coverage405406For tasks checking SBAR (Situation, Background, Assessment, Recommendation)407coverage: examine the service request or referral documentation for all408four sections. `complete` is `true` only when all four are present. List409any missing sections explicitly in `missing_sections`.410411## Audit Logs412413For merge packets, look for audit entries that document duplicate414candidate lifecycle events, patient record merges, or identity reviews.415Sort audit IDs alphabetically in evidence arrays.416417## Exclusion of Distractors418419The environment includes distractor records. Exclude these from output:420421- **Inactive clinical records**: conditions, medications, or allergies422 with status `inactive`, `resolved`, or `entered-in-error` stay out of423 active lists.424- **Unrelated documents**: generic chart summaries and documents for425 unrelated patients or workflows.426- **Stale encounters**: encounters outside the relevant time window or427 purely administrative encounters.428- **Irrelevant audit logs**: entries for unrelated operations.429430When the template has an `excluded_distractors` section, populate it with431the specific keys or IDs that were reviewed and excluded.432433## Packet Readiness Assessment434435Every packet concludes with a readiness assessment:436437- `ready` / `ready_to_send`: all required data is present, valid, and438 permits the action. No blocking issues.439- `ready_with_risk_flags` / `ready_with_review_note`: substantially440 complete but with noted risks the recipient should see. Still safe441 to send.442- `not_ready` / `blocked` / `hold_for_*`: one or more blocking issues443 prevent sending. Report the specific issue codes from the template's444 allowed values.445446A packet is ready only when all required entities exist, all required447documents are received in final status, authorizations are approved448(or not required), disclosures are permitted, and provider assignments449are resolved.450451## Overall Workflow452453For any EHR quality-governance task, follow this sequence:4544551. **Read the answer template** fully. Note every field, type, enum456 constraint, and sorting rule.4574582. **Identify the task type** from the prompt (merge packet, referral459 coordination, care transition, duplicate review, or referral audit).4604613. **Fetch core entities** in parallel where possible: patients, the462 primary business object (duplicate candidate, referral, service463 request), and relevant providers.4644654. **Fetch clinical data** for every involved patient: conditions,466 medications, allergies — filtered to active status.4674685. **Fetch supporting data** as needed: encounters, documents,469 immunizations, disclosures, audit logs, ICD-10 codes, service codes.4704716. **Validate and reconcile**: check ICD-10 chapters against service472 lines, compare laterality and narrative, cross-reference identity473 signals with demographics, verify document statuses, confirm474 authorization states, and validate provider service lines.4754767. **Build the output JSON** field by field following the template477 exactly. Apply sorting. Respect enum constraints. Exclude distractors.4784798. **Verify before returning**: every required key is present, every480 array that should be sorted is sorted, every enum matches the481 allowed values, no explanatory text appears outside the JSON, and482 every summary count matches its source array length.483484## Common Pitfalls485486- **Not filtering by status**: always check for `status: "active"` when487 gathering active clinical lists; inactive records are distractors.488- **Including chart summaries as evidence**: `chart_summary` documents are489 internal — exclude them from packet evidence.490- **Wrong laterality**: verify every ICD-10 code's laterality against the491 directory entry; do not guess from memory.492- **Swapping target and source in merges**: target is the canonical record493 to preserve; source is the duplicate to absorb.494- **Skipping duplicate-preview reconciliation**: always cross-check the495 duplicate candidate's preview lists against individual patient endpoints.496- **Omitting duplicate rows from Tier 1**: when duplicate-tiering policy says497 to block all duplicate rows, both the original and resubmission must appear.498- **Empty arrays vs. omitted keys**: emit `[]` for empty array fields; never499 omit the key or use `null`.500- **Inconsistent summary counts**: every count must equal the length of the501 corresponding array elsewhere in the output.