EHR Quality-Governance Packet Builder
Use this skill when the task requires calling a read-only EHR REST API and
producing a normalized JSON packet that conforms to an answer template. The
templates describe the required shape; your job is to collect the right evidence
from the endpoints and fill in the fields correctly.
Environment Setup
A <TASK_ENV_BASE_URL> placeholder appears in the prompt. It resolves to a
base URL (default http://task-env:9015/). All endpoints are GET, read-only,
no authentication. Verify the base is reachable with GET /health before
collecting data.
Available Endpoints
Every task environment exposes a subset of these endpoints. Use the ones the
prompt or template references; do not call endpoints that are absent from the
prompt's allowed list.
Patient and clinical lists:
GET /api/patients — patient search and listing
GET /api/patients/{patient_id} — single patient demographics
GET /api/patients/{patient_id}/conditions — active/inactive problem-list conditions
GET /api/patients/{patient_id}/medications — active/inactive medication orders
GET /api/patients/{patient_id}/allergies — allergy/intolerance records
GET /api/patients/{patient_id}/encounters — encounter history
GET /api/patients/{patient_id}/immunizations — immunization records
GET /api/patients/{patient_id}/documents — clinical documents
GET /api/patients/{patient_id}/service-requests — ServiceRequest resources
GET /api/patients/{patient_id}/disclosures — disclosure/consent records
Quality-governance and operational:
GET /api/audit-logs — audit trail entries
GET /api/duplicates/candidates — duplicate candidate listing
GET /api/duplicates/{candidate_id} — single duplicate candidate detail
GET /api/referrals — referral search/list
GET /api/referrals/{referral_id} — single referral detail
Code systems and directories:
GET /api/icd10 — ICD-10 code directory
GET /api/icd10/{code} — single ICD-10 code lookup (returns chapter, description)
GET /api/providers — provider directory listing
GET /api/providers/{provider_id} — single provider detail
GET /api/service-codes — service/procedure code directory
GET /api/service-codes/{code} — single service code validation
Entity Model and Field Conventions
Patients
A patient record has a patient_id (like P-31014), enterprise_mrn,
display name, date of birth, sex, insurance ID, phone, address, and
primary_care_provider_id. Demographics (dob, insurance_id, phone, sex,
address, given name) are the basis for identity-match and identity-conflict
signals in duplicate review.
Conditions (Problem List)
Each condition has:
code — ICD-10 code (e.g. E11.9, I10, M17.11)
description — human-readable text
normalized_key — a stable, lowercase, snake_case identifier (e.g.
diabetes_type_2, hypertension, right_knee_oa, memory_loss)
status — active or inactive
source — problem_list, referral_intake, or other origin
Only active conditions belong in clinical union sets for merge and
transition packets. Inactive conditions are excluded or placed in distractor
lists. When the template asks for active_condition_keys, extract the
normalized_key from every active record, drop duplicates, and sort
alphabetically.
Medications
Structure mirrors conditions: medication (name string), normalized_key
(snake_case, e.g. aspirin, insulin_glargine, baseline_med), status
(active/inactive), and optional dose, route, frequency. Only active
medications go into union sets; inactive ones are excluded.
Allergies
Structure: allergen, reaction, severity (mild/moderate/severe/unknown),
status (active/inactive/entered-in-error/unknown), source,
and normalized_key (e.g. penicillin, latex, iodinated_contrast,
baseline_allergy). Active allergies only for packet-ready lists.
Encounters
Each encounter has encounter_id, date (YYYY-MM-DD), type (e.g.
office_visit, care_transition), provider_id, signed_status
(signed/unsigned/amended/draft), diagnosis_codes (array of ICD-10
codes), medications_mentioned, and care_plan_tag.
For handoff/transition packets, select encounters from a defined window. Sort
selected encounters newest-to-oldest; excluded encounters are sorted ascending
by encounter_id.
Documents
Fields: document_id, type (e.g. echocardiogram, office_note,
chart_summary), date, status (final/preliminary/cancelled).
When the packet documents a duplicate merge, include only identity-related or
external-continuity documents. Exclude chart_summary types unless the answer
template explicitly asks for them.
Duplicate Candidates
A duplicate candidate record links two patients: a primary patient and a
possible duplicate. It contains match_signals (why they might be the same
person) and conflict_signals (why they might not be). Common match signals:
same_dob, same_insurance, same_phone, similar_address, same_given_name.
Common conflict signals: different_given_name, different_phone,
different_dob, different_insurance, different_address,
opposite_laterality_problem.
The candidate's candidate_status may be confirmed_duplicate, needs_review,
or not_duplicate.
Referrals
A referral record connects a patient to a diagnosis code and a receiving
provider. Key fields: referral_id, patient_id, batch_id, service_line,
requested_date, diagnosis_code, diagnosis_narrative, urgency
(routine/urgent/stat), referral_status
(open/closed/cancelled/draft), authorization_status
(approved/pending/denied/not_required/unknown), receiving_provider_id.
Service Requests
A ServiceRequest (FHIR-style) has: service_request_id, patient_id, status
(draft/active/on-hold/revoked/completed/entered-in-error), intent
(order/plan/proposal/etc.), priority (routine/urgent/asap/stat),
service_code, requester_provider_id, performer_provider_id,
authored_on, occurrence_date, reason_codes (array of ICD-10 codes).
Providers
A provider record has: provider_id (e.g. PRV-PCP-001, PRV-CARD-020,
PRV-ORTHO-010), name, role, service_line, facility, phone, fax.
ICD-10 Codes
ICD-10 lookup returns a code, description, and chapter (e.g.
Musculoskeletal, Circulatory, Endocrine, Injury, Respiratory). Codes
have laterality encoded in specific digits (e.g. M17.11 vs M17.12 for right
vs left knee osteoarthritis; S83.241A vs S83.242A for right vs left medial
meniscus tear). The chapter tells you whether a code belongs to the expected
service line.
General Methodology
Follow this order for every task:
Read the answer template first. Understand every required top-level key,
every enum, and every array ordering rule. The template is the contract.
Read the prompt's task-specific instructions. Note the case objects
(patient IDs, candidate IDs, referral IDs, provider IDs, ServiceRequest IDs)
the task gives you.
Call the API endpoints to collect evidence. Start with the entity the
task names (patient, duplicate candidate, referral, batch) then fan out to
related resources. Use parallel calls when endpoints are independent.
Validate codes and cross-reference. For every ICD-10 code, look it up
in /api/icd10/{code} to confirm it exists and belongs to the expected
chapter. For every service code, validate against /api/service-codes/{code}.
For every provider reference, confirm the provider exists via
/api/providers/{provider_id}.
Produce the normalized JSON. Fill in every required field. Use the
normalized_key field from API responses for condition/medication/allergy
lists. Sort arrays marked as sets alphabetically. Use enum values exactly as
the template spells them. When the template allows null for a field, use
JSON null (not the string "null").
Return JSON only. The output must be a single JSON object with no
surrounding prose, markdown fences, or commentary.
Task-Type Rules
Duplicate Merge Readiness Packet
Given a candidate_id and two patient_ids, determine whether the duplicate
pair should merge and build the merge packet.
Call GET /api/duplicates/{candidate_id} to get match signals, conflict
signals, and candidate status.
Call both patients' demographics endpoints, then their conditions,
medications, allergies, documents, and encounters endpoints in parallel.
Merge decision: The target is the patient with the active canonical
record. The source is the other patient. If the duplicate candidate record
already points one patient as duplicate-of-the-other, that determines the
direction. Disposition is ready_to_merge when identity signals outweigh
conflicts and no blocker exists; needs_review when conflicts are present
but mitigable; do_not_merge when conflicts dominate.
Clinical unions: Build the set-union of normalized_key values from
active conditions, active medications, and active allergies across both
patients. Sort each list alphabetically. Compare what the duplicate preview
shows against what the individual patient active-list endpoints return; any
key present in the patient endpoints but missing from the duplicate preview
goes into *_added_from_active_endpoints.
Identity signals: Translate the duplicate candidate's match and conflict
signals into the template's signal labels. Also check demographics:
identical fields across both patients are demographic matches; differing
fields are demographic conflicts.
Documents: Select only documents that establish identity linkage or
represent external continuity-of-care records shared between the two shells.
Exclude chart summaries and unrelated internal documents. List excluded
documents in the distractor set.
Audit logs: Call GET /api/audit-logs and collect entries that trace
the duplicate candidate or the merge review activity. List them as evidence.
Provider contacts: Identify the specialist referenced by any external
continuity document on the source patient's shell. Also identify each
patient's primary care provider.
Packet readiness: ready when all evidence is collected and no blocker
remains. List blocker codes when issues exist.
Referral Coordination Packet
Given a referral_id and patient_id, reconcile the referral against the
patient chart and produce the coordination packet.
Call GET /api/referrals/{referral_id} for referral detail. Call
/api/patients/{patient_id} and all clinical-list endpoints for the patient.
Active diagnoses: List every active condition from the patient's problem
list, plus any diagnosis code supplied directly by the referral intake.
Mark each as referral_relevant when it maps to the referral's service line
or matches the referral's own diagnosis codes.
Referral code set: The primary code is the referral's own diagnosis code.
Supporting codes are additional codes relevant to the referral narrative.
Validate every code against /api/icd10/{code}. The icd_validation field
is valid_matches_narrative when the code exists, belongs to the expected
service chapter, and its description matches the referral narrative;
valid_but_narrative_mismatch when the code is valid but the narrative
diverges; invalid_code when the code is not found; wrong_service_chapter
when the code's chapter does not match the service line.
Allergy readiness: Collect active allergies. Status is
complete_documented when allergy information is consistent and non-empty.
Use no_known_allergies when the records explicitly state none.
conflicting_allergy_records when sources disagree.
Recent encounter evidence: Pick the most recent signed encounter that
references the referral's diagnosis codes or care plan. Include its
encounter_id, date, type, provider, signed_status, diagnosis_codes, and
medications_mentioned.
Required documents: Check whether the expected documents for this service
line exist (echo for cardiology, imaging for orthopedics). List missing
required document types.
Receiving provider: Look up the provider from the referral record via
/api/providers/{provider_id}.
Authorization: Check the referral's authorization_status and referral_status.
Overall readiness is ready_to_send when authorization is approved, documents
are present, and no clinical mismatches block it.
Medication highlights: List active medications relevant to the referral's
clinical context. Use the highlight_reason enum values to explain why each one
matters.
Referral letter fields: Map each decision into the appropriate enum
choice for the letter template. The choices should be consistent with the
evidence above.
Care Transition Packet
Given a patient_id and recipient_provider_id, produce a handoff packet for
a surgical or specialty transition.
Call /api/patients/{patient_id} for demographics. Call all clinical-list
endpoints in parallel.
Call /api/providers/{recipient_provider_id} for recipient details.
Active clinical lists: Extract normalized_key values from active
conditions, medications, and allergies. Sort alphabetically.
Handoff encounters: Filter encounters to signed encounters within a
relevant window (typically 60-90 days preceding the transition). Select the
four most recent. For orthopedic surgery transitions, care_transition
encounters and recent office_visit encounters are preferred. Sort selected
encounters newest-to-oldest by date. List any reviewed-but-excluded
encounter IDs as stale/outside-window.
Latest immunization: Pick the most recent immunization by date.
Disclosure: Find the disclosure record that matches the recipient
provider and purpose (surgical handoff, care transition). Confirm it is
in permitted status.
Risk flags: Identify risks from the clinical evidence. Common flags:
cognitive_memory_loss (from conditions like memory loss), fall_risk_note_required
(from lower-extremity OA conditions), hypertension (from hypertension
condition), insulin_dependent_diabetes (from diabetes with insulin),
latex_allergy (from latex allergy record), perioperative_glucose_plan_needed
(from diabetes plus surgical context). Each risk flag must have evidence:
which conditions, medications, and encounter IDs support it.
Packet readiness: ready when all sections are populated and no blocker
exists; ready_with_risk_flags when all sections are complete but risk flags
are present; not_ready when a required section is missing.
Quality-Governance Duplicate + ServiceRequest Review
Given a duplicate candidate, two patient IDs, and a ServiceRequest ID, produce
a combined review packet.
Call /api/duplicates/{candidate_id} for the duplicate review.
Call /api/patients/{patient_id}/service-requests and
/api/service-codes/{service_code} to validate the ServiceRequest.
Duplicate review section: Extract match and conflict signals from the
candidate record. When identity signals are weak (different names, different
phones, opposing laterality in conditions) and no strong override exists, set
decision to review_hold and merge_target_patient_id /
merge_source_patient_id to null. Only set merge when the candidate is
confirmed and identity evidence is strong.
ServiceRequest section: Validate every field from the SR record. Validate
the service code against the directory. For each reason code, look it up with
/api/icd10/{code} and record whether it is valid, which chapter it belongs to,
and whether it matches the patient's clinical evidence (active conditions,
recent encounters).
SBAR coverage: Determine whether the ServiceRequest contains Situation,
Background, Assessment, and Recommendation sections. The complete field is
true only when all four are present.
Batch Referral Audit
Given a batch_id and service_line, audit every referral in the batch.
Call /api/referrals (with batch or date filters) to list all referrals in
the batch. Count total rows and unique patients.
For every referral, call /api/icd10/{diagnosis_code} to get the ICD-10
chapter. Out-of-range detection: The expected chapter for the service
line is implied by the service line itself — e.g. orthopedics expects
Musculoskeletal chapter codes. Codes from Injury, Respiratory,
Circulatory, or other non-matching chapters are out-of-range. Codes not
found in the ICD-10 directory are unknown_code.
Laterality/narrative mismatch: Compare the ICD-10 description
(laterality, body site, condition) against the referral's diagnosis_narrative.
Types of mismatch:
laterality_mismatch: the code implies one side (left/right) but the
narrative describes the other side or a different body part.
narrative_mismatch: the code's condition (e.g. meniscus tear) does not
match the narrative's condition (e.g. lumbar radiculopathy).
missing_laterality: the code encodes laterality but the narrative omits it.
The expected_terms array should contain the ICD-10 description or known
aliases from the code lookup that the narrative should have matched.
Duplicate groups: Scan for referrals that share the same patient_id in
the same batch. Same-patient resubmissions form duplicate groups. The
tier_1_duplicate_blocker_referral_ids includes all referrals in the
duplicate group. Separate same-patient referrals that represent distinct
clinical reviews go into separate_same_patient_referral_ids.
Insurance anomalies: When two different patients share the same
insurance_id, flag as shared_insurance_different_patients with
recommended_disposition of verify_insurance_membership_do_not_merge.
Follow-up queues: Build four arrays of referral_ids:
authorization_missing: referrals with no authorization or denied.
authorization_pending: referrals with pending authorization.
records_request: referrals missing required office-note documents.
imaging_follow_up: referrals missing or needing imaging.
Action plan: Assign every referral with an unresolved issue to one of
three tiers:
- Tier 1: Duplicate-blocker referrals and referrals with urgent coding
issues. Primary reason:
urgent_coding_or_duplicate_blocker.
- Tier 2: Referrals with routine coding mismatches, missing
authorization, or missing documents. Primary reason:
routine_coding_auth_or_document_blocker.
- Tier 3: Referrals that only need administrative document completion.
Primary reason:
administrative_document_completion.
Assign an owner_provider_id for each tier entry. Use the batch's
orthopedic providers (look them up via /api/providers if needed).
Summary counts: Compute each integer count from the audit data. The
validated_ready_no_follow_up_count is the number of referrals with no issues
in any category.
Output Rules
JSON only. No explanations, no markdown fences, no trailing text.
Alphabetically sorted arrays. When the template says "sort alphabetically"
or "set semantics", sort string arrays with standard ASCII ordering. Numeric
ids prefixed by letters sort naturally. Exception: when the template orders by
date newest-to-oldest.
Enums are exact. Use the exact string values from the template. Never
invent a new enum variant.
Booleans are true / false, not strings. Same for null — use JSON
null, not "null".
Dates use YYYY-MM-DD format.
Normalized keys are always lowercase snake_case, pulled directly from the
API response's normalized_key field. Never invent your own key name.
Exclude distractors. When a record is inactive, stale, outside the window,
or unrelated to the packet's clinical scope, exclude it from the active lists
and (where the template calls for it) list it in the excluded/distractor
arrays.
Cross-validate. ICD-10 validation, service-code validation, provider
lookups, and disclosure recipient checks are not optional. If the API returns
data that contradicts the prompt's stated case objects, the API data is the
authority.
Default selections. When multiple choices are reasonable (e.g. which
provider to assign in a tier), prefer the provider most closely connected to
the referral or patient. When no connection is obvious, spread assignments
across the relevant service-line providers.
Common Pitfalls
Active vs inactive: Always filter by status: "active" before building
clinical union sets. Inactive records go to distractor lists or are omitted.
Baseline records: The API may include records with normalized_key like
baseline_med or baseline_allergy. These are real active records; include
them in unions and exclude them from distractors.
Duplicate candidate direction: The duplicate candidate's record tells you
which patient is the primary and which is the possible duplicate. Do not
reverse this in the merge decision. When the candidate status is
needs_review, both merge target and source may remain null.
Chapter validation for orthopedics: Orthopedic referrals expect
Musculoskeletal chapter codes. ICD-10 S codes are in the Injury chapter,
not Musculoskeletal. A referral with an S code for an orthopedic service
line is an out-of-range chapter issue unless the context explicitly states
otherwise.
Laterality encoding in ICD-10: Know that the sixth character often encodes
laterality: 1 = right, 2 = left in many musculoskeletal codes. Check the
actual ICD-10 description from the API lookup; do not assume from the code
digits alone.
Insurance anomalies are not duplicates. Shared insurance across different
patients is an anomaly to flag, not a duplicate to merge.
Document selection: Do not include every document from a patient chart.
Select only those that serve the packet's purpose (identity linkage, external
continuity, required specialty evidence). Chart summaries are generally
excluded unless the template explicitly requires them.
1---2name: ehr-quality-governance-93description: Build normalized JSON packets for EHR quality-governance tasks (duplicate merge, referral coordination, care transition, ServiceRequest review, batch audit) by calling a read-only healthcare REST API and producing template-conformant output.4metadata:5 source: https://skillmd.com/skills/prism-shadow/ehr-quality-governance-96---78# EHR Quality-Governance Packet Builder910Use this skill when the task requires calling a read-only EHR REST API and11producing a normalized JSON packet that conforms to an answer template. The12templates describe the required shape; your job is to collect the right evidence13from the endpoints and fill in the fields correctly.1415## Environment Setup1617A `<TASK_ENV_BASE_URL>` placeholder appears in the prompt. It resolves to a18base URL (default `http://task-env:9015/`). All endpoints are GET, read-only,19no authentication. Verify the base is reachable with `GET /health` before20collecting data.2122### Available Endpoints2324Every task environment exposes a subset of these endpoints. Use the ones the25prompt or template references; do not call endpoints that are absent from the26prompt's allowed list.2728**Patient and clinical lists:**29- `GET /api/patients` — patient search and listing30- `GET /api/patients/{patient_id}` — single patient demographics31- `GET /api/patients/{patient_id}/conditions` — active/inactive problem-list conditions32- `GET /api/patients/{patient_id}/medications` — active/inactive medication orders33- `GET /api/patients/{patient_id}/allergies` — allergy/intolerance records34- `GET /api/patients/{patient_id}/encounters` — encounter history35- `GET /api/patients/{patient_id}/immunizations` — immunization records36- `GET /api/patients/{patient_id}/documents` — clinical documents37- `GET /api/patients/{patient_id}/service-requests` — ServiceRequest resources38- `GET /api/patients/{patient_id}/disclosures` — disclosure/consent records3940**Quality-governance and operational:**41- `GET /api/audit-logs` — audit trail entries42- `GET /api/duplicates/candidates` — duplicate candidate listing43- `GET /api/duplicates/{candidate_id}` — single duplicate candidate detail44- `GET /api/referrals` — referral search/list45- `GET /api/referrals/{referral_id}` — single referral detail4647**Code systems and directories:**48- `GET /api/icd10` — ICD-10 code directory49- `GET /api/icd10/{code}` — single ICD-10 code lookup (returns chapter, description)50- `GET /api/providers` — provider directory listing51- `GET /api/providers/{provider_id}` — single provider detail52- `GET /api/service-codes` — service/procedure code directory53- `GET /api/service-codes/{code}` — single service code validation5455## Entity Model and Field Conventions5657### Patients5859A patient record has a `patient_id` (like `P-31014`), `enterprise_mrn`,60display name, date of birth, sex, insurance ID, phone, address, and61`primary_care_provider_id`. **Demographics** (dob, insurance_id, phone, sex,62address, given name) are the basis for identity-match and identity-conflict63signals in duplicate review.6465### Conditions (Problem List)6667Each condition has:68- `code` — ICD-10 code (e.g. `E11.9`, `I10`, `M17.11`)69- `description` — human-readable text70- `normalized_key` — a stable, lowercase, snake_case identifier (e.g.71 `diabetes_type_2`, `hypertension`, `right_knee_oa`, `memory_loss`)72- `status` — `active` or `inactive`73- `source` — `problem_list`, `referral_intake`, or other origin7475Only **active** conditions belong in clinical union sets for merge and76transition packets. Inactive conditions are excluded or placed in distractor77lists. When the template asks for `active_condition_keys`, extract the78`normalized_key` from every active record, drop duplicates, and sort79alphabetically.8081### Medications8283Structure mirrors conditions: `medication` (name string), `normalized_key`84(snake_case, e.g. `aspirin`, `insulin_glargine`, `baseline_med`), `status`85(`active`/`inactive`), and optional `dose`, `route`, `frequency`. Only active86medications go into union sets; inactive ones are excluded.8788### Allergies8990Structure: `allergen`, `reaction`, `severity` (`mild`/`moderate`/`severe`/`unknown`),91`status` (`active`/`inactive`/`entered-in-error`/`unknown`), `source`,92and `normalized_key` (e.g. `penicillin`, `latex`, `iodinated_contrast`,93`baseline_allergy`). Active allergies only for packet-ready lists.9495### Encounters9697Each encounter has `encounter_id`, `date` (YYYY-MM-DD), `type` (e.g.98`office_visit`, `care_transition`), `provider_id`, `signed_status`99(`signed`/`unsigned`/`amended`/`draft`), `diagnosis_codes` (array of ICD-10100codes), `medications_mentioned`, and `care_plan_tag`.101102For handoff/transition packets, select encounters from a defined window. Sort103selected encounters newest-to-oldest; excluded encounters are sorted ascending104by encounter_id.105106### Documents107108Fields: `document_id`, `type` (e.g. `echocardiogram`, `office_note`,109`chart_summary`), `date`, `status` (`final`/`preliminary`/`cancelled`).110111When the packet documents a duplicate merge, include only identity-related or112external-continuity documents. Exclude `chart_summary` types unless the answer113template explicitly asks for them.114115### Duplicate Candidates116117A duplicate candidate record links two patients: a primary patient and a118possible duplicate. It contains `match_signals` (why they might be the same119person) and `conflict_signals` (why they might not be). Common match signals:120`same_dob`, `same_insurance`, `same_phone`, `similar_address`, `same_given_name`.121Common conflict signals: `different_given_name`, `different_phone`,122`different_dob`, `different_insurance`, `different_address`,123`opposite_laterality_problem`.124125The candidate's `candidate_status` may be `confirmed_duplicate`, `needs_review`,126or `not_duplicate`.127128### Referrals129130A referral record connects a patient to a diagnosis code and a receiving131provider. Key fields: `referral_id`, `patient_id`, `batch_id`, `service_line`,132`requested_date`, `diagnosis_code`, `diagnosis_narrative`, `urgency`133(`routine`/`urgent`/`stat`), `referral_status`134(`open`/`closed`/`cancelled`/`draft`), `authorization_status`135(`approved`/`pending`/`denied`/`not_required`/`unknown`), `receiving_provider_id`.136137### Service Requests138139A ServiceRequest (FHIR-style) has: `service_request_id`, `patient_id`, `status`140(`draft`/`active`/`on-hold`/`revoked`/`completed`/`entered-in-error`), `intent`141(`order`/`plan`/`proposal`/etc.), `priority` (`routine`/`urgent`/`asap`/`stat`),142`service_code`, `requester_provider_id`, `performer_provider_id`,143`authored_on`, `occurrence_date`, `reason_codes` (array of ICD-10 codes).144145### Providers146147A provider record has: `provider_id` (e.g. `PRV-PCP-001`, `PRV-CARD-020`,148`PRV-ORTHO-010`), `name`, `role`, `service_line`, `facility`, `phone`, `fax`.149150### ICD-10 Codes151152ICD-10 lookup returns a `code`, `description`, and `chapter` (e.g.153`Musculoskeletal`, `Circulatory`, `Endocrine`, `Injury`, `Respiratory`). Codes154have laterality encoded in specific digits (e.g. `M17.11` vs `M17.12` for right155vs left knee osteoarthritis; `S83.241A` vs `S83.242A` for right vs left medial156meniscus tear). The chapter tells you whether a code belongs to the expected157service line.158159## General Methodology160161Follow this order for every task:1621631. **Read the answer template first.** Understand every required top-level key,164 every enum, and every array ordering rule. The template is the contract.1651662. **Read the prompt's task-specific instructions.** Note the case objects167 (patient IDs, candidate IDs, referral IDs, provider IDs, ServiceRequest IDs)168 the task gives you.1691703. **Call the API endpoints to collect evidence.** Start with the entity the171 task names (patient, duplicate candidate, referral, batch) then fan out to172 related resources. Use parallel calls when endpoints are independent.1731744. **Validate codes and cross-reference.** For every ICD-10 code, look it up175 in `/api/icd10/{code}` to confirm it exists and belongs to the expected176 chapter. For every service code, validate against `/api/service-codes/{code}`.177 For every provider reference, confirm the provider exists via178 `/api/providers/{provider_id}`.1791805. **Produce the normalized JSON.** Fill in every required field. Use the181 `normalized_key` field from API responses for condition/medication/allergy182 lists. Sort arrays marked as sets alphabetically. Use enum values exactly as183 the template spells them. When the template allows null for a field, use184 JSON `null` (not the string `"null"`).1851866. **Return JSON only.** The output must be a single JSON object with no187 surrounding prose, markdown fences, or commentary.188189## Task-Type Rules190191### Duplicate Merge Readiness Packet192193Given a `candidate_id` and two `patient_ids`, determine whether the duplicate194pair should merge and build the merge packet.1951961. Call `GET /api/duplicates/{candidate_id}` to get match signals, conflict197 signals, and candidate status.1981992. Call both patients' demographics endpoints, then their conditions,200 medications, allergies, documents, and encounters endpoints in parallel.2012023. **Merge decision:** The target is the patient with the active canonical203 record. The source is the other patient. If the duplicate candidate record204 already points one patient as duplicate-of-the-other, that determines the205 direction. Disposition is `ready_to_merge` when identity signals outweigh206 conflicts and no blocker exists; `needs_review` when conflicts are present207 but mitigable; `do_not_merge` when conflicts dominate.2082094. **Clinical unions:** Build the set-union of `normalized_key` values from210 active conditions, active medications, and active allergies across both211 patients. Sort each list alphabetically. Compare what the duplicate preview212 shows against what the individual patient active-list endpoints return; any213 key present in the patient endpoints but missing from the duplicate preview214 goes into `*_added_from_active_endpoints`.2152165. **Identity signals:** Translate the duplicate candidate's match and conflict217 signals into the template's signal labels. Also check demographics:218 identical fields across both patients are demographic matches; differing219 fields are demographic conflicts.2202216. **Documents:** Select only documents that establish identity linkage or222 represent external continuity-of-care records shared between the two shells.223 Exclude chart summaries and unrelated internal documents. List excluded224 documents in the distractor set.2252267. **Audit logs:** Call `GET /api/audit-logs` and collect entries that trace227 the duplicate candidate or the merge review activity. List them as evidence.2282298. **Provider contacts:** Identify the specialist referenced by any external230 continuity document on the source patient's shell. Also identify each231 patient's primary care provider.2322339. **Packet readiness:** `ready` when all evidence is collected and no blocker234 remains. List blocker codes when issues exist.235236### Referral Coordination Packet237238Given a `referral_id` and `patient_id`, reconcile the referral against the239patient chart and produce the coordination packet.2402411. Call `GET /api/referrals/{referral_id}` for referral detail. Call242 `/api/patients/{patient_id}` and all clinical-list endpoints for the patient.2432442. **Active diagnoses:** List every active condition from the patient's problem245 list, plus any diagnosis code supplied directly by the referral intake.246 Mark each as `referral_relevant` when it maps to the referral's service line247 or matches the referral's own diagnosis codes.2482493. **Referral code set:** The primary code is the referral's own diagnosis code.250 Supporting codes are additional codes relevant to the referral narrative.251 Validate every code against `/api/icd10/{code}`. The `icd_validation` field252 is `valid_matches_narrative` when the code exists, belongs to the expected253 service chapter, and its description matches the referral narrative;254 `valid_but_narrative_mismatch` when the code is valid but the narrative255 diverges; `invalid_code` when the code is not found; `wrong_service_chapter`256 when the code's chapter does not match the service line.2572584. **Allergy readiness:** Collect active allergies. Status is259 `complete_documented` when allergy information is consistent and non-empty.260 Use `no_known_allergies` when the records explicitly state none.261 `conflicting_allergy_records` when sources disagree.2622635. **Recent encounter evidence:** Pick the most recent signed encounter that264 references the referral's diagnosis codes or care plan. Include its265 encounter_id, date, type, provider, signed_status, diagnosis_codes, and266 medications_mentioned.2672686. **Required documents:** Check whether the expected documents for this service269 line exist (echo for cardiology, imaging for orthopedics). List missing270 required document types.2712727. **Receiving provider:** Look up the provider from the referral record via273 `/api/providers/{provider_id}`.2742758. **Authorization:** Check the referral's authorization_status and referral_status.276 Overall readiness is `ready_to_send` when authorization is approved, documents277 are present, and no clinical mismatches block it.2782799. **Medication highlights:** List active medications relevant to the referral's280 clinical context. Use the highlight_reason enum values to explain why each one281 matters.28228310. **Referral letter fields:** Map each decision into the appropriate enum284 choice for the letter template. The choices should be consistent with the285 evidence above.286287### Care Transition Packet288289Given a `patient_id` and `recipient_provider_id`, produce a handoff packet for290a surgical or specialty transition.2912921. Call `/api/patients/{patient_id}` for demographics. Call all clinical-list293 endpoints in parallel.2942952. Call `/api/providers/{recipient_provider_id}` for recipient details.2962973. **Active clinical lists:** Extract `normalized_key` values from active298 conditions, medications, and allergies. Sort alphabetically.2993004. **Handoff encounters:** Filter encounters to signed encounters within a301 relevant window (typically 60-90 days preceding the transition). Select the302 four most recent. For orthopedic surgery transitions, `care_transition`303 encounters and recent `office_visit` encounters are preferred. Sort selected304 encounters newest-to-oldest by date. List any reviewed-but-excluded305 encounter IDs as stale/outside-window.3063075. **Latest immunization:** Pick the most recent immunization by date.3083096. **Disclosure:** Find the disclosure record that matches the recipient310 provider and purpose (`surgical handoff`, `care transition`). Confirm it is311 in `permitted` status.3123137. **Risk flags:** Identify risks from the clinical evidence. Common flags:314 `cognitive_memory_loss` (from conditions like memory loss), `fall_risk_note_required`315 (from lower-extremity OA conditions), `hypertension` (from hypertension316 condition), `insulin_dependent_diabetes` (from diabetes with insulin),317 `latex_allergy` (from latex allergy record), `perioperative_glucose_plan_needed`318 (from diabetes plus surgical context). Each risk flag must have evidence:319 which conditions, medications, and encounter IDs support it.3203218. **Packet readiness:** `ready` when all sections are populated and no blocker322 exists; `ready_with_risk_flags` when all sections are complete but risk flags323 are present; `not_ready` when a required section is missing.324325### Quality-Governance Duplicate + ServiceRequest Review326327Given a duplicate candidate, two patient IDs, and a ServiceRequest ID, produce328a combined review packet.3293301. Call `/api/duplicates/{candidate_id}` for the duplicate review.3313322. Call `/api/patients/{patient_id}/service-requests` and333 `/api/service-codes/{service_code}` to validate the ServiceRequest.3343353. **Duplicate review section:** Extract match and conflict signals from the336 candidate record. When identity signals are weak (different names, different337 phones, opposing laterality in conditions) and no strong override exists, set338 `decision` to `review_hold` and `merge_target_patient_id` /339 `merge_source_patient_id` to `null`. Only set `merge` when the candidate is340 confirmed and identity evidence is strong.3413424. **ServiceRequest section:** Validate every field from the SR record. Validate343 the service code against the directory. For each reason code, look it up with344 `/api/icd10/{code}` and record whether it is valid, which chapter it belongs to,345 and whether it matches the patient's clinical evidence (active conditions,346 recent encounters).3473485. **SBAR coverage:** Determine whether the ServiceRequest contains Situation,349 Background, Assessment, and Recommendation sections. The `complete` field is350 `true` only when all four are present.351352### Batch Referral Audit353354Given a `batch_id` and `service_line`, audit every referral in the batch.3553561. Call `/api/referrals` (with batch or date filters) to list all referrals in357 the batch. Count total rows and unique patients.3583592. For every referral, call `/api/icd10/{diagnosis_code}` to get the ICD-10360 chapter. **Out-of-range detection:** The expected chapter for the service361 line is implied by the service line itself — e.g. `orthopedics` expects362 `Musculoskeletal` chapter codes. Codes from `Injury`, `Respiratory`,363 `Circulatory`, or other non-matching chapters are out-of-range. Codes not364 found in the ICD-10 directory are `unknown_code`.3653663. **Laterality/narrative mismatch:** Compare the ICD-10 description367 (laterality, body site, condition) against the referral's `diagnosis_narrative`.368 Types of mismatch:369 - `laterality_mismatch`: the code implies one side (left/right) but the370 narrative describes the other side or a different body part.371 - `narrative_mismatch`: the code's condition (e.g. meniscus tear) does not372 match the narrative's condition (e.g. lumbar radiculopathy).373 - `missing_laterality`: the code encodes laterality but the narrative omits it.374375 The `expected_terms` array should contain the ICD-10 description or known376 aliases from the code lookup that the narrative should have matched.3773784. **Duplicate groups:** Scan for referrals that share the same patient_id in379 the same batch. Same-patient resubmissions form duplicate groups. The380 `tier_1_duplicate_blocker_referral_ids` includes all referrals in the381 duplicate group. Separate same-patient referrals that represent distinct382 clinical reviews go into `separate_same_patient_referral_ids`.3833845. **Insurance anomalies:** When two different patients share the same385 insurance_id, flag as `shared_insurance_different_patients` with386 `recommended_disposition` of `verify_insurance_membership_do_not_merge`.3873886. **Follow-up queues:** Build four arrays of referral_ids:389 - `authorization_missing`: referrals with no authorization or denied.390 - `authorization_pending`: referrals with pending authorization.391 - `records_request`: referrals missing required office-note documents.392 - `imaging_follow_up`: referrals missing or needing imaging.3933947. **Action plan:** Assign every referral with an unresolved issue to one of395 three tiers:396 - **Tier 1**: Duplicate-blocker referrals and referrals with urgent coding397 issues. Primary reason: `urgent_coding_or_duplicate_blocker`.398 - **Tier 2**: Referrals with routine coding mismatches, missing399 authorization, or missing documents. Primary reason:400 `routine_coding_auth_or_document_blocker`.401 - **Tier 3**: Referrals that only need administrative document completion.402 Primary reason: `administrative_document_completion`.403 Assign an `owner_provider_id` for each tier entry. Use the batch's404 orthopedic providers (look them up via `/api/providers` if needed).4054068. **Summary counts:** Compute each integer count from the audit data. The407 `validated_ready_no_follow_up_count` is the number of referrals with no issues408 in any category.409410## Output Rules411412- **JSON only.** No explanations, no markdown fences, no trailing text.413414- **Alphabetically sorted arrays.** When the template says "sort alphabetically"415 or "set semantics", sort string arrays with standard ASCII ordering. Numeric416 ids prefixed by letters sort naturally. Exception: when the template orders by417 date newest-to-oldest.418419- **Enums are exact.** Use the exact string values from the template. Never420 invent a new enum variant.421422- **Booleans are `true` / `false`, not strings.** Same for `null` — use JSON423 `null`, not `"null"`.424425- **Dates use YYYY-MM-DD format.**426427- **Normalized keys** are always lowercase snake_case, pulled directly from the428 API response's `normalized_key` field. Never invent your own key name.429430- **Exclude distractors.** When a record is inactive, stale, outside the window,431 or unrelated to the packet's clinical scope, exclude it from the active lists432 and (where the template calls for it) list it in the excluded/distractor433 arrays.434435- **Cross-validate.** ICD-10 validation, service-code validation, provider436 lookups, and disclosure recipient checks are not optional. If the API returns437 data that contradicts the prompt's stated case objects, the API data is the438 authority.439440- **Default selections.** When multiple choices are reasonable (e.g. which441 provider to assign in a tier), prefer the provider most closely connected to442 the referral or patient. When no connection is obvious, spread assignments443 across the relevant service-line providers.444445## Common Pitfalls446447- **Active vs inactive:** Always filter by `status: "active"` before building448 clinical union sets. Inactive records go to distractor lists or are omitted.449450- **Baseline records:** The API may include records with `normalized_key` like451 `baseline_med` or `baseline_allergy`. These are real active records; include452 them in unions and exclude them from distractors.453454- **Duplicate candidate direction:** The duplicate candidate's record tells you455 which patient is the primary and which is the possible duplicate. Do not456 reverse this in the merge decision. When the candidate status is457 `needs_review`, both merge target and source may remain `null`.458459- **Chapter validation for orthopedics:** Orthopedic referrals expect460 `Musculoskeletal` chapter codes. ICD-10 `S` codes are in the `Injury` chapter,461 not `Musculoskeletal`. A referral with an `S` code for an orthopedic service462 line is an out-of-range chapter issue unless the context explicitly states463 otherwise.464465- **Laterality encoding in ICD-10:** Know that the sixth character often encodes466 laterality: `1` = right, `2` = left in many musculoskeletal codes. Check the467 actual ICD-10 description from the API lookup; do not assume from the code468 digits alone.469470- **Insurance anomalies are not duplicates.** Shared insurance across different471 patients is an anomaly to flag, not a duplicate to merge.472473- **Document selection:** Do not include every document from a patient chart.474 Select only those that serve the packet's purpose (identity linkage, external475 continuity, required specialty evidence). Chart summaries are generally476 excluded unless the template explicitly requires them.