[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M713AVGGKAEMZSYBW9W300EX":3,"skill-same:01M713AVGGKAEMZSYBW9W300EX":81},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":40,"linkOnly":41,"markdownContent":42,"markdownBody":43,"frontMatter":44,"refName":45,"commitSha":46,"skillDirectory":47,"forksCount":48,"repositoryHtmlUrl":49,"repositoryHomepageUrl":6,"ownerHtmlUrl":50,"ownerBlogUrl":6,"ownerDescription":51,"updatedAt":52,"install":53,"resources":66},"01M713AVGGKAEMZSYBW9W300EX","nhi-cql-generator",null,"Generate CQL Library and FHIR ValueSet artifacts for Taiwan NHI (National Health Insurance) reimbursement rules from rule text. Use when user asks to create CQL\u002FValueSet for 健保給付規則, 藥品審查, NHI CQL, 健保代碼, or payment審查. This skill applies patterns learned from 50+ GT examples.","FDU-INS\u002FInsurance-Skills","FDU-INS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F167067594?v=4","01M6XEYMRS4CVJMZ834YWE66BV","FDU-Insurance","01M6XEYMXPDA34HFM0ZE6AY78G",82,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FFDU-INS\u002FInsurance-Skills\u002Fblob\u002Fmain\u002FSkills\u002Fnhi-cql-generator\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FFDU-INS\u002FInsurance-Skills\u002Fblob\u002Fmain\u002FSkills\u002Fnhi-cql-generator\u002FSKILL.md",[],[20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39],"nhi cql generator","cql","generator","use","insurance","when","for","rule","learned","patterns","health insurance","Rules","text","fhir","health","examples","library","artifacts","generate","create","2026-11-10 10:12:30",false,"---\nname: nhi-cql-generator\ndescription: Generate CQL Library and FHIR ValueSet artifacts for Taiwan NHI (National Health Insurance) reimbursement rules from rule text. Use when user asks to create CQL\u002FValueSet for 健保給付規則, 藥品審查, NHI CQL, 健保代碼, or payment審查. This skill applies patterns learned from 50+ GT examples.\n---\n\n# NHI CQL Generator\n\nGenerate CQL Library (.cql) and FHIR ValueSet (.json) files from Taiwan NHI reimbursement rules text.\n\n## Overview\n\nThis skill generates standardized clinical decision support artifacts for Taiwan's National Health Insurance system:\n1. **CQL Library** - Clinical Quality Language for payment審查邏輯\n2. **FHIR ValueSet** - Code sets (適應症, 禁忌症, 藥品, etc.)\n3. **Dependency Libraries** - Required CQL libraries that must accompany every generated CQL file\n\n**Critical**: All patterns are learned from 50+ GT examples. Do NOT deviate from documented patterns.\n\n### Required Dependency Libraries\n\nEvery generated CQL file depends on two shared libraries located in `.github\u002Fskills\u002Fnhi-cql-generator\u002Fassets\u002F`:\n\n1. **FHIRHelpers.cql** (version 4.0.1)\n   - Provides FHIR data model interaction helpers\n   - Converts FHIR types to CQL types\n   - Required by all FHIR-based CQL libraries\n\n2. **CDSConnectCommonsForFHIRv401.cql** (version 2.1.0, aliased as C3F)\n   - Provides common clinical decision support functions that can be used directly\n   - **Frequently used functions**:\n     * `C3F.Confirmed(Conditions)` - Filter confirmed conditions\n     * `C3F.Verified(Observations)` - Filter verified observations  \n     * `C3F.MostRecent(Observations)` - Get most recent observation\n     * `C3F.QuantityValue(Observation)` - Extract quantity value\n     * `C3F.ObservationLookBack(Observations, LookBack)` - Observations in time window\n     * `C3F.MostRecentProcedure(Procedures)` - Get most recent procedure\n     * `C3F.ActiveCondition(Conditions)` - Filter active conditions\n     * `C3F.PeriodToInterval(Period)` - Convert FHIR Period to CQL Interval\n   - **Usage**: Directly use C3F functions with the `C3F.` prefix (e.g., `C3F.Confirmed([Condition: \"code\"])`)\n   - **Note**: GT examples redundantly redefine these functions, but this is unnecessary - you should use C3F functions directly\n\n**IMPORTANT**: When generating CQL artifacts, you MUST copy these two files to the output directory alongside the generated `.cql` files. Without them, the CQL will fail with error:\n```\nCould not load source for library CDSConnectCommonsForFHIRv401, version 2.1.0, namespace uri null.\n```\n\n## CQL Structure Patterns\n\n### Library Declaration\n\n```cql\nlibrary \"[規則編號]\" version '0.0.1'\n```\n\n- **Library name**: Exact rule code (e.g., \"08111B\", \"12216C\", \"69041B\")\n- **Version**: Always `'0.0.1'`\n\n### Standard Headers (Fixed Order)\n\n```cql\nlibrary \"[規則編號]\" version '0.0.1'\n\nusing FHIR version '4.0.1'\n\ninclude \"FHIRHelpers\" version '4.0.1' called FHIRHelpers\ninclude \"CDSConnectCommonsForFHIRv401\" version '2.1.0' called C3F\n```\n\n**Never change**: FHIR version, FHIRHelpers version, C3F version, or aliases.\n\n### ValueSet Declarations\n\nAfter include statements, before codesystem declarations:\n\n```cql\nvalueset \"[中文名稱] valueset\": '[ValueSet URL]'\n```\n\n**URL Pattern**: `https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.[sequential-number]`\n\n**Examples**:\n- `valueset \"17022B 呼氣一氧化氮監測(FeNO) valueset\": 'https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.6'`\n- `valueset \"糖尿病合併慢性腎病變 valueset\": 'https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.46'`\n\n### CodeSystem URLs (Complete Approved List)\n\nUse **ONLY** these codesystem URLs:\n\n```cql\ncodesystem \"ICD-10-CM\": 'http:\u002F\u002Fhl7.org\u002Ffhir\u002Fsid\u002Ficd-10-cm'\ncodesystem \"ICD-10-PCS\": 'http:\u002F\u002Fwww.cms.gov\u002FMedicare\u002FCoding\u002FICD10'\ncodesystem \"LOINC\": 'http:\u002F\u002Floinc.org'\ncodesystem \"SCT\": 'http:\u002F\u002Fsnomed.info\u002Fsct'\ncodesystem \"TWMedicalServicePayment\": 'https:\u002F\u002Ftwcore.mohw.gov.tw\u002Fig\u002Ftwcore\u002FCodeSystem\u002Fmedical-service-payment-tw'\ncodesystem \"CONDVERSTATUS\": 'http:\u002F\u002Fterminology.hl7.org\u002FCodeSystem\u002Fcondition-ver-status'\ncodesystem \"CONDCLINSTATUS\": 'http:\u002F\u002Fterminology.hl7.org\u002FCodeSystem\u002Fcondition-clinical'\ncodesystem \"ActCode\": 'http:\u002F\u002Fterminology.hl7.org\u002FCodeSystem\u002Fv3-ActCode'\n```\n\n### Context Declaration\n\n```cql\ncontext Patient\n```\n\nAlways use `Patient` context.\n\n### Define Statements Pattern\n\n**Standard structure** observed in all examples:\n\n```cql\ndefine \"[適應症或條件名稱]\":\n  exists ( C3F.Confirmed([Condition: \"[valueset名稱]\"]) )\n\ndefine \"MeetsInclusionCriteria\":\n  \"[主要適應症]\"\n  \ndefine \"InPopulation\":\n  \"MeetsInclusionCriteria\"\n\ndefine \"Recommendation\":\n  if \"InPopulation\" then '健保給付[點數]點' \n    else null\n\ndefine \"Rationale\":\n  null\n\ndefine \"Links\":\n  null\n\ndefine \"Suggestions\":\n  null\n\ndefine \"Errors\":\n  null\n```\n\n### Using C3F Helper Functions\n\n**Direct Usage** - Use C3F library functions directly without redefining them:\n\n```cql\n\u002F\u002F ✅ Correct: Use C3F functions directly\ndefine \"適應症\":\n  exists ( C3F.Confirmed([Condition: \"適應症 valueset\"]) )\n\ndefine \"Recent Observations\":\n  C3F.ObservationLookBack([Observation: \"code\"], 1 year)\n\ndefine \"Lab Value\":\n  C3F.QuantityValue( C3F.MostRecent([Observation: \"code\"]) )\n```\n\n**Common C3F Functions**:\n- `C3F.Confirmed(Conditions)` - Filters to confirmed conditions (verificationStatus = 'confirmed')\n- `C3F.Verified(Observations)` - Filters to verified observations (status = 'final', 'corrected', or 'amended')\n- `C3F.ObservationLookBack(Observations, LookBack)` - Observations within time window\n- `C3F.MostRecent(Observations)` - Most recent observation by effective date\n- `C3F.QuantityValue(Observation)` - Extract quantity value from observation\n- `C3F.MostRecentProcedure(Procedures)` - Most recent procedure\n- `C3F.ActiveCondition(Conditions)` - Active conditions (clinicalStatus = 'active', no abatement)\n- `C3F.PeriodToInterval(Period)` - Convert FHIR Period to CQL Interval\n\n**Note**: GT examples redundantly redefine these functions at the end of each file, but this is **unnecessary duplication**. Simply use `C3F.FunctionName()` directly.\n\n## Common Logic Patterns\n\n### Condition Checking\n\n```cql\nexists ( C3F.Confirmed([Condition: \"[valueset名稱]\"]) )\n```\n\n### Multiple Conditions (OR)\n\n```cql\nexists ( C3F.Confirmed([Condition: \"valueset1\"])\n    union C3F.Confirmed([Condition: \"valueset2\"])\n)\n```\n\n### Multiple Conditions (AND)\n\n```cql\n\"condition1\" and \"condition2\"\n```\n\n### Observation with Time Window\n\n```cql\nCount(C3F.ObservationLookBack([Observation: \"[code]\"], 1 year)) \u003C 3\n```\n\n### Age Checking\n\n```cql\nAgeInYears() >= 6 and AgeInYears() \u003C 13\n```\n\n### Encounter with Specialty\n\n```cql\n[Encounter: \"[valueset]\"] E\n  where ( E.serviceType ~ \"[specialty code]\" )\n```\n\n### Procedure Lookback (using C3F)\n\n```cql\nC3F.ProcedureLookBack([Procedure: \"[code]\"], 6 months)\n```\n\n### Nested Conditionals (for複雜給付條件)\n\n```cql\ndefine \"Recommendation\":\n  if \"condition1\" then if \"condition2\" then '說明A'\n    else '說明B'\n  else if \"condition3\" then '說明C'\n  else null\n```\n\n### Subpopulations Pattern\n\nFor rules with multiple適應症 with different頻率:\n\n```cql\ndefine \"subpopulation 1\":\n  if \"InPopulation\" is not true then null \n    else [specific condition for subpop1]\n\ndefine \"subpopulation 2\":\n  if \"InPopulation\" is not true then null \n    else [specific condition for subpop2]\n    \ndefine \"Recommendation\":\n  if \"subpopulation 1\" then '健保給付[點數]點，[規範1]'\n  else if \"subpopulation 2\" then '健保給付[點數]點，[規範2]'\n  else null\n```\n\n## Medical Knowledge Mapping\n\n### Spinal Disorders Coding\n\nWhen rules mention \"脊髓損傷或病變\", include **ALL** three categories:\n\n| Category | ICD-10-CM | Examples |\n|----------|-----------|----------|\n| **Trauma** | S14.*, S24.*, S34.*, S44.* | Spinal cord injury |\n| **Disease** | G95.*, G82.* | Spinal cord disorders, paraplegia |\n| **Degeneration** | M43.3, M47.1, M50.0, M51.0 | Spondylolisthesis, myelopathy, disc disorders |\n\n**Critical**: \"病變\" includes both functional disease (G-codes) AND degenerative structural changes (M-codes).\n\n### Stroke Sequelae Coding\n\nFor \"腦中風後遺症\" or \"中風導致之肢體偏癱\":\n\n| Scope | ICD-10-CM | Purpose |\n|-------|-----------|---------|\n| **General stroke** | I69.* | All stroke sequelae |\n| **Hemiplegia types** | I69.33-I69.35 | Dominant\u002Fnon-dominant\u002Funspecified side |\n| **Specific sequelae** | I69.3, I69.33, I69.34, I69.35, I69.39 | Cerebral infarction aftereffects |\n\n**Pattern**: Use I69.* for broad inclusion, add specific I69.3X codes when hemiplegia is explicitly mentioned.\n\n### Peripheral Neuropathy\n\nFor \"周邊神經病變\":\n\n- **Diabetic**: E11.4* (Type 2 DM with neurological complications)\n- **General**: G62.* (polyneuropathy), G63.* (neuropathy in diseases)\n- **Specific**: G62.9 (unspecified polyneuropathy)\n\n### Observation Value Checking Pattern\n\nFor laboratory or measurement constraints:\n\n```cql\ndefine \"低密度脂蛋白膽固醇異常\":\n  exists (\n    [Observation: \"LOINC code 18262-6\"] O\n      where O.value as Quantity > 100 'mg\u002FdL'\n        and O.status = 'final'\n  )\n```\n\n### Complex Age Range Checks\n\nFor rules specifying age ranges with measurement timing:\n\n```cql\ndefine \"符合年齡條件\":\n  ( AgeInYears() >= 10 and AgeInYears() \u003C= 17 )\n    or ( AgeInYears() >= 6 and AgeInYears() \u003C 10 and \"已測量過基線值\" )\n```\n\n## Code Style Rules\n\n- **Indentation**: 2 spaces (NO tabs)\n- **String quotes**: Single quotes `'...'` for all strings\n- **Line breaks**: Blank line between major sections (valuesets, codesystems, context, defines)\n- **Comments**: Use `\u002F\u002F` sparingly, written in Chinese when explaining業務邏輯\n- **Naming**: Chinese variable names permitted (e.g., `define \"氣喘\":`, `define \"懷孕糖尿病人、妊娠糖尿病人\":`)\n- **Boolean checks**: Use `\"variable\"` not `\"variable\" = true`\n\n## NHI Rule Text Parsing\n\n### Rule ID Format\n\nPattern: `[數字]{2,5}[字母]` (e.g., 08111B, 12216C, 69041B, 83102K)\n\n### Common Phrases to Extract\n\n**適應症 (Indications)**:\n- \"適應症：\", \"適應症包括：\"\n- \"限...使用\", \"限...申報\"\n- \"適用於...\", \"符合...\"\n\n**禁忌症 (Contraindications)**:\n- \"禁忌症：\", \"不得用於...\"\n- \"排除...\", \"不適用\"\n\n**支付規範 (Payment Rules)**:\n- \"支付規範：\", \"執行頻率：\"\n- \"每[時間]限申報[次數]次\"\n- \"一年限申報[數字]次\"\n- \"不得同時申報...\"\n\n**點數 (Points)**:\n- \"[數字]點\" (e.g., \"800點\", \"17350點\")\n\n**專科限制 (Specialty)**:\n- \"限...專科醫師\", \"限由...執行\"\n\n### Diagnosis Code Extraction\n\nFrom text patterns like:\n- \"多發性硬化症、運動神經元疾病、脊髓損傷...\" → Create valueset for ICD-10-CM codes\n- \"四肢自體動脈粥樣硬化（I70.2～I70.7）\" → Code range with all subcodes\n- \"糖尿病酮酸中毒\" → Look up ICD-10-CM code\n\n### Frequency Constraints Encoding\n\n**CRITICAL**: Always filter by the **specific NHI procedure code** using `TWMedicalServicePayment` codesystem. NEVER use bare `[Procedure]` (this would match ALL procedures, not the one being regulated).\n\n#### Required: Declare procedure code at top of file\n\n```cql\ncodesystem \"TWMedicalServicePayment\": 'https:\u002F\u002Ftwcore.mohw.gov.tw\u002Fig\u002Ftwcore\u002FCodeSystem\u002Fmedical-service-payment-tw'\n\ncode \"[代號] 健保給付代碼\": '[代號]' from \"TWMedicalServicePayment\" display '[項目名稱]'\n```\n\n#### Frequency check pattern\n\n```cql\n\u002F\u002F ✅ Correct: counts only THIS specific procedure\ndefine \"頻率符合\":\n  Count(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 1 year)) \u003C N\n\n\u002F\u002F ❌ WRONG: counts ALL procedures in the patient's history\ndefine \"頻率符合\":\n  Count(C3F.ProcedureLookBack([Procedure], 1 year)) \u003C N\n```\n\n| Rule Text | CQL Encoding |\n|-----------|--------------|\n| \"一年限申報三次\" | `Count(ObservationLookBack([Observation: ...], 1 year)) \u003C 3` |\n| \"每四年限申報一次\" | `Count(ObservationLookBack([Observation: ...], 4 years)) \u003C 1` |\n| \"每人以申報一次為原則\" | Track across patient lifetime |\n| \"每次就診...每次治療應間隔至少一週\" | Date diff checking |\n| \"一年限申報三次\" | `Count(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 1 year)) \u003C 3` |\n| \"每四年限申報一次\" | `Count(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 4 years)) \u003C 1` |\n| \"每人以申報一次為原則\" | `not exists(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 100 years))` |\n| \"每週最多N次\" | `Count(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 7 days)) \u003C N` |\n| \"每月限一次\" | `Count(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 30 days)) \u003C 1` |\n\n#### Per-Encounter \u002F Per-Hospitalization check\n\nWhen the rule says **\"限住院期間申報一次\"** or **\"同一就診申報一次\"**, use Encounter reference instead of a time window. A time window (e.g., \"1 year\") would incorrectly block re-admission for a new event.\n\n```cql\n\u002F\u002F 取得目前就醫 Encounter（最近一次進行中或完成的）\ndefine \"目前住院Encounter\":\n  Last(\n    [Encounter] E\n      where E.status = 'in-progress' or E.status = 'finished'\n      sort by start of period\n  )\n\n\u002F\u002F 本次住院期間尚未申報過本項目\ndefine \"本次住院未申報過\":\n  \"目前住院Encounter\" is not null\n    and not exists(\n      [Procedure: \"[代號] 健保給付代碼\"] P\n        where P.encounter.reference = 'Encounter\u002F' + \"目前住院Encounter\".id\n    )\n```\n\n#### \"同一治療期間\" (Episode of Care) check\n\nWhen rule says **\"同一治療期間至多N次\"**, the ideal boundary is `EpisodeOfCare`. As a pragmatic approximation, use Encounter-reference for the per-visit part, and ProcedureLookBack with a reasonable lookback window for the total-count part:\n\n```cql\ndefine \"本次就診未申報\":\n  \"目前住院Encounter\" is not null\n    and not exists(\n      [Procedure: \"[代號] 健保給付代碼\"] P\n        where P.encounter.reference = 'Encounter\u002F' + \"目前住院Encounter\".id\n    )\n\n\u002F\u002F 治療期間總次數：以 1 年作為最長治療期間的保守估計\ndefine \"治療期間總次數符合\":\n  Count(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 1 year)) \u003C N\n```\n\n> **Note**: The ideal approach for \"同一治療期間\" is to use `EpisodeOfCare`, but this requires the FHIR server to populate `EpisodeOfCare` resources. The time-window approximation is the practical fallback.\n\n### Other Regulation Handling (其他規範處理)\n\n**Critical**: Distinguish between **pre-authorization criteria** (事前資格檢查) and **post-payment rules** (事後支付規則).\n\n#### Type 1: Pre-Authorization Criteria → Convert to CQL Logic\n\nThese MUST be encoded as executable logic in MeetsInclusionCriteria:\n\n**Pattern: Contraindication** (\"禁忌症：...\")\n\nWhen a rule lists contraindications, create a **separate contraindication ValueSet** and check for absence:\n\n```cql\n\u002F\u002F 1. Declare a separate contraindication valueset\nvalueset \"[代號] 禁忌症\": 'https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.[n]'\n\n\u002F\u002F 2. Define the contraindication check\ndefine \"有禁忌症\":\n  exists ( C3F.Confirmed([Condition: \"[代號] 禁忌症\"]) )\n\n\u002F\u002F 3. Incorporate into MeetsInclusionCriteria\ndefine \"MeetsInclusionCriteria\":\n  \"Has Indication\" and not \"有禁忌症\"\n\n\u002F\u002F 4. Recommendation branches (always check indication first → then contraindication)\ndefine \"Recommendation\":\n  if not \"Has Indication\" then null\n    else if \"有禁忌症\" then '不得申報。病患符合禁忌症：[詳細原因]。'\n    else '健保給付。...'\n```\n\n**Important**: The contraindication JSON file uses the same structure as the indication ValueSet. Give it a **distinct OID number** (e.g., indication = `.9`, contraindication = `.200`).\n\n**Pattern: Specialist Restriction** (\"限...專科醫師執行\")\n\n```cql\ncodesystem \"SCT\": 'http:\u002F\u002Fsnomed.info\u002Fsct'\n\ncode \"Specialist code\": '[SNOMED-code]' from \"SCT\" display '[specialist-type]'\n\ndefine \"performer_id\":\n  Last(Split(First(\"RecentProcedure\".performer).actor.reference, '\u002F'))\n\ndefine \"Performer_ref\":\n  [Practitioner] P where P.id = \"performer_id\"\n\ndefine \"Qualified_Practitioner\":\n  exists ( \"Performer_ref\".qualification q\n    where q.code ~ \"Specialist code\" )\n\ndefine \"MeetsInclusionCriteria\":\n  \"[適應症]\" and \"Qualified_Practitioner\"\n```\n\n**Examples**:\n- \"限外科專科醫師執行\" → SNOMED CT: 224555008 (Vascular surgeon)\n- \"限兒科專科\" → SNOMED CT: 24251000087109 (General pediatric specialty)\n- \"限心臟血管外科\" → SNOMED CT: 309296001 (Cardiac surgeon)\n\n**Pattern: Procedure Type Restriction**\n\nWhen rule specifies specific surgical procedures:\n\n```cql\ncodesystem \"ICD-10-PCS\": 'http:\u002F\u002Fwww.cms.gov\u002FMedicare\u002FCoding\u002FICD10'\n\ncode \"Procedure1 code\": '[code]' from \"ICD-10-PCS\" display '[description]'\ncode \"Procedure2 code\": '[code]' from \"ICD-10-PCS\" display '[description]'\n\ndefine \"ApplicableProcedure\":\n  C3F.MostRecentProcedure ( [Procedure: \"Procedure1 code\"]\n    union [Procedure: \"Procedure2 code\"]\n  )\n\ndefine \"MeetsInclusionCriteria\":\n  \"[適應症]\" and exists(\"ApplicableProcedure\")\n```\n\n**Pattern: Encounter Specialty Check**\n\nFor rules limiting to specific clinical departments:\n\n```cql\ncode \"Department specialty code\": '[SNOMED-code]' from \"SCT\" display '[specialty]'\n\ndefine \"SpecialtyEncounter\":\n  [Encounter] E where E.serviceType ~ \"Department specialty code\"\n\ndefine \"encounter check\":\n  exists(\"SpecialtyEncounter\")\n\ndefine \"Recommendation\":\n  if \"InPopulation\" is not true then null\n    else if \"encounter check\" then '給付'\n    else '非[科別]申報，不予給付'\n```\n\n#### Type 2: Post-Payment Rules → Include in Recommendation Text Only\n\nThese should appear in Recommendation string but NOT in MeetsInclusionCriteria:\n\n**Examples**:\n- \"一般材料費得另加計百分之五十\" → Include in Recommendation only\n- \"應事先申請\" → Include in Recommendation only\n- \"需檢附...報告\" → Include in Recommendation only\n- \"不得同時申報...\" → Include in Recommendation as note\n\n**Pattern**:\n```cql\ndefine \"Recommendation\":\n  if \"InPopulation\" then '健保給付[點數]點，[描述]，一般材料費得另加計百分之五十'\n  else null\n```\n\n#### Decision Logic: When to Convert to CQL vs Text Only\n\n| Phrase Pattern | Type | Action |\n|---------------|------|--------|\n| 限...專科醫師執行 | Pre-auth | ✅ Convert to Practitioner.qualification check |\n| 限...科別申報 | Pre-auth | ✅ Convert to Encounter.serviceType check |\n| 限特定手術類型 | Pre-auth | ✅ Convert to Procedure code check |\n| 材料費加計...% | Post-payment | ❌ Text only in Recommendation |\n| 應事先申請 | Administrative | ❌ Text only in Recommendation |\n| 需檢附報告 | Administrative | ❌ Text only in Recommendation |\n\n**Critical Rule**: If the regulation affects **whether payment is approved**, it's pre-authorization → convert to CQL. If it only affects **how much** or **when** to pay, it's post-payment → text only.\n\n## ValueSet Generation\n\n### ValueSet JSON Template\n\nBased on GT examples, use this complete structure:\n\n```json\n{\n  \"resourceType\": \"ValueSet\",\n  \"id\": \"2.16.840.1.113762.1.4.1287.[number]\",\n  \"meta\": {\n    \"versionId\": \"1\",\n    \"lastUpdated\": \"[timestamp]\",\n    \"profile\": [\n      \"http:\u002F\u002Fhl7.org\u002Ffhir\u002FStructureDefinition\u002Fshareablevalueset\",\n      \"http:\u002F\u002Fhl7.org\u002Ffhir\u002Fus\u002Fcqfmeasures\u002FStructureDefinition\u002Fcomputable-valueset-cqfm\",\n      \"http:\u002F\u002Fhl7.org\u002Ffhir\u002Fus\u002Fcqfmeasures\u002FStructureDefinition\u002Fpublishable-valueset-cqfm\"\n    ]\n  },\n  \"extension\": [\n    {\n      \"url\": \"http:\u002F\u002Fhl7.org\u002Ffhir\u002FStructureDefinition\u002Fvalueset-author\",\n      \"valueContactDetail\": {\n        \"name\": \"Industrial Technology Research Institute Author\"\n      }\n    },\n    {\n      \"url\": \"http:\u002F\u002Fhl7.org\u002Ffhir\u002FStructureDefinition\u002Fresource-lastReviewDate\",\n      \"valueDate\": \"[YYYY-MM-DD]\"\n    },\n    {\n      \"url\": \"http:\u002F\u002Fhl7.org\u002Ffhir\u002FStructureDefinition\u002Fvalueset-effectiveDate\",\n      \"valueDate\": \"[YYYY-MM-DD]\"\n    }\n  ],\n  \"url\": \"http:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.[number]\",\n  \"identifier\": [\n    {\n      \"system\": \"urn:ietf:rfc:3986\",\n      \"value\": \"urn:oid:2.16.840.1.113762.1.4.1287.[number]\"\n    }\n  ],\n  \"version\": \"[YYYYMMDD]\",\n  \"name\": \"[EnglishCamelCaseName]\",\n  \"title\": \"[English title or Chinese title]\",\n  \"status\": \"active\",\n  \"date\": \"[timestamp]\",\n  \"publisher\": \"Industrial Technology Research Institute Steward\",\n  \"description\": \"[規則編號，可多個用逗號分隔如 63007B, 63008B]\",\n  \"jurisdiction\": [\n    {\n      \"extension\": [\n        {\n          \"url\": \"http:\u002F\u002Fhl7.org\u002Ffhir\u002FStructureDefinition\u002Fdata-absent-reason\",\n          \"valueCode\": \"unknown\"\n        }\n      ]\n    }\n  ],\n  \"purpose\": \"(Clinical Focus: ...),(Data Element Scope: ...),(Inclusion Criteria: ...),(Exclusion Criteria: ...)\",\n  \"compose\": {\n    \"include\": [\n      {\n        \"system\": \"[CodeSystem URL]\",\n        \"version\": \"2025\",\n        \"filter\": [\n          {\n            \"property\": \"concept\",\n            \"op\": \"[operator]\",\n            \"value\": \"[code]\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### ID Naming Convention\n\nPattern: `2.16.840.1.113762.1.4.1287.[sequential-number]`\n\nThe ID is the **full OID**, not a custom name. File name matches the ID:\n- File: `2.16.840.1.113762.1.4.1287.6.json`\n- ID: `\"2.16.840.1.113762.1.4.1287.6\"`\n\n### URL Pattern\n\n**Critical**: Use `http:\u002F\u002F` (NOT `https:\u002F\u002F`) in url field:\n```json\n\"url\": \"http:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.[number]\"\n```\n\n**In CQL**: Use `https:\u002F\u002F` in valueset declarations:\n```cql\nvalueset \"name\": 'https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.[number]'\n```\n\n### Filter Operators (from GT examples)\n\nUse `filter` instead of explicit `concept` array:\n\n**Common operators**:\n- `\"op\": \"descendent-of\"` - Include code and all descendants (most common)\n- `\"op\": \"is-a\"` - Include code and descendants\n- `\"op\": \"=\"` - Exact match single code\n- `\"op\": \"in\"` - Multiple codes (comma-separated in value)\n\n**Examples**:\n```json\n\u002F\u002F All J45.* asthma codes\n{\"property\": \"concept\", \"op\": \"descendent-of\", \"value\": \"J45\"}\n\n\u002F\u002F Specific codes\n{\"property\": \"concept\", \"op\": \"=\", \"value\": \"C79.81\"}\n\n\u002F\u002F Multiple specific codes\n{\"property\": \"concept\", \"op\": \"in\", \"value\": \"E10.22,E13.22,E08.22\"}\n```\n\n### Filter Operator Selection Strategy\n\nChoose operator based on code specificity and clinical intent:\n\n| Operator | Use When | ICD-10 Code Pattern | Example |\n|----------|----------|---------------------|---------|\n| **`=`** | Exact leaf code needed | 6-7 digits (e.g., G62.9, I69.398) | Single specific diagnosis |\n| **`is-a`** | Mid-level category | 4-5 digits (e.g., J45.5, E11.4) | Specific subtype with few children |\n| **`descendent-of`** | Broad family inclusion | 3-4 digits (e.g., J45, I69, G62) | All variants needed |\n| **`in`** | Multiple unrelated codes | Mixed | Enumerate disparate codes |\n\n**Code Granularity Guidelines**:\n- **Preferred**: Mid-level codes (5-6 digits) - balance precision and coverage\n- **Avoid**: Too broad (3 digits: J45 vs J45.*) or too narrow (7+ digits)\n- **Quick judgment**: Code length 3-4 → descendent-of; 5-6 → is-a; 7+ → =\n\n**Real Examples from GT**:\n```json\n\u002F\u002F G62.9 (7 digits, leaf code) - use exact match\n{\"property\": \"concept\", \"op\": \"=\", \"value\": \"G62.9\"}\n\n\u002F\u002F E11.4 (5 digits, mid-level) - use is-a\n{\"property\": \"concept\", \"op\": \"is-a\", \"value\": \"E11.4\"}\n\n\u002F\u002F I69 (3 digits, broad family) - use descendent-of\n{\"property\": \"concept\", \"op\": \"descendent-of\", \"value\": \"I69\"}\n\n\u002F\u002F Multiple unrelated codes - use in\n{\"property\": \"concept\", \"op\": \"in\", \"value\": \"M43.3,M47.1,M50.0,M51.0\"}\n```\n\n**Decision Logic**:\n1. If code explicitly ends with .0, .9, or has 6+ digits → `=`\n2. If code has 4-5 digits and represents specific subtype → `is-a`\n3. If code is 3-4 digits and needs all variants → `descendent-of`\n4. If multiple disparate codes listed → `in`\n\n### Purpose Field Format\n\nStandard 4-part structure (observed in all GT examples):\n\n```\n(Clinical Focus: [臨床焦點]),(Data Element Scope: [資料元素範圍]),(Inclusion Criteria: [納入條件]),(Exclusion Criteria: [排除條件，若無則寫 No])\n```\n\n**Critical**: ValueSet.url in JSON **must exactly match** the valueset declaration URL in CQL (except http vs https).\n\n### Common ValueSet Types\n\n1. **Diagnosis codes** (ICD-10-CM) - Most common\n   - System: `http:\u002F\u002Fhl7.org\u002Ffhir\u002Fsid\u002Ficd-10-cm`\n   - Version: `\"2025\"`\n   - Use filters, not explicit concept lists\n2. **Procedure codes** (ICD-10-PCS or TWMedicalServicePayment)\n   - System: `http:\u002F\u002Fwww.cms.gov\u002FMedicare\u002FCoding\u002FICD10` or `https:\u002F\u002Ftwcore.mohw.gov.tw\u002Fig\u002Ftwcore\u002FCodeSystem\u002Fmedical-service-payment-tw`\n3. **Lab tests** (LOINC)\n   - System: `http:\u002F\u002Floinc.org`\n4. **Clinical findings** (SNOMED CT)\n   - System: `http:\u002F\u002Fsnomed.info\u002Fsct`\n\n### Multiple Rules Sharing Same ValueSet\n\nFrom GT examples, one ValueSet may support multiple rules:\n- `\"description\": \"63007B, 63008B\"` - Modified radical mastectomy (single\u002Fbilateral)\n- `\"description\": \"13030B,13031B,13032B\"` - Different H. pylori tests\n\nWhen rules share indications, use the same ValueSet ID.\n\n## Workflow\n\n### Step 1: Collect Input\n\nAsk user for:\n- **規則編號** (Rule ID) - e.g., \"08111B\"\n- **完整給付規則文字** (Full rule text including適應症, 禁忌症, 支付規範, 點數)\n\n### Step 2: Parse Rule Text\n\nExtract and identify:\n- Rule ID\n- 點數 (reimbursement points)\n- 適應症 (indications) - list of diagnoses\u002Fconditions\n- 禁忌症 (contraindications) - if any\n- 執行頻率限制 (frequency limits)\n- 不得同時申報項目 (cannot claim with)\n- 專科限制 (specialty restrictions)\n- 其他支付規範 (other payment rules)\n\n### Step 3: Generate ValueSets\n\nFor **each distinct code set** identified:\n\n1. Create JSON file: `2.16.840.1.113762.1.4.1287.[number].json`\n2. Use complete template structure from GT examples\n3. Assign sequential OID number\n4. Set url with `http:\u002F\u002F` (NOT https)\n5. Populate filter operators based on code patterns:\n   - Use `descendent-of` for code families (e.g., J45 for all asthma)\n   - Use `in` for multiple specific codes\n   - Use `=` for single specific codes\n6. Fill purpose field with 4-part structure\n7. Save with UTF-8 encoding\n\n**Important**: \n- File name = full OID (e.g., `2.16.840.1.113762.1.4.1287.6.json`)\n- url field uses `http:\u002F\u002F` \n- CQL valueset declaration uses `https:\u002F\u002F`\n\n### Step 4: Generate CQL Library\n\nFollowing exact structure:\n\n1. Library declaration with rule ID\n2. using FHIR version\n3. include statements (FHIRHelpers, C3F)\n4. valueset declarations (URLs must match JSON files)\n5. codesystem declarations\n6. Standard code\u002Fconcept for Confirmed\n7. context Patient\n8. define statements (適應症, conditions, InPopulation, Recommendation, etc.)\n9. Standard define statements (Rationale, Links, Suggestions, Errors as null)\n10. All five helper functions\n\n### Step 5: Validate Generated Files\n\nChecklist:\n\n- ✓ CQL valueset declaration URLs **exactly match** ValueSet JSON url fields\n- ✓ Only codesystem URLs from approved list used\n- ✓ All five helper functions included at end\n- ✓ Structure follows examples (headers, blank lines, 2-space indentation)\n- ✓ Recommendation includes 點數 and key給付規範\n- ✓ File encoding is UTF-8\n- ✓ No tabs, only spaces\n\n### Step 6: Provide Output\n\nDeliver to user:\n\n1. **CQL file**: `[規則編號].cql` (plain text)\n2. **ValueSet file(s)**: One or more `2.16.840.1.113762.1.4.1287.[number].json` files\n3. **Dependency libraries**: Copy from `.github\u002Fskills\u002Fnhi-cql-generator\u002Fassets\u002F` to output directory:\n   - `FHIRHelpers.cql`\n   - `CDSConnectCommonsForFHIRv401.cql`\n4. **Mapping table**: \n\n```markdown\n| CQL ValueSet Declaration | ValueSet File | URL (CQL uses https, JSON uses http) |\n|--------------------------|---------------|---------------------------------------|\n| [中文名稱] valueset | 2.16.840.1.113762.1.4.1287.[N].json | https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.[N] |\n```\n\n5. **Validation report**: Confirm all patterns followed ✓\n\n**Critical**: The CQL file will NOT execute without the dependency libraries in the same directory. Always include them in the output.\n\n## Examples\n\n### Example 1: Simple Rule (08111B)\n\n**Input**: \n- Rule ID: 08111B\n- 點數: 800點\n- 適應症: 凝血異常，疑有Von-willebrands disease者\n\n**Output**:\n- `08111B.cql` - With Von Willebrand disease codes\n- `2.16.840.1.113762.1.4.1287.1.json` - ICD-10-CM codes with filter for VWD codes\n\n### Example 2: Rule with Frequency (17022B)\n\n**Input**:\n- Rule ID: 17022B\n- 點數: 748點  \n- 適應症: 六歲以上至未滿十三歲確診氣喘患者追蹤使用\n- 頻率: 一年最多申報三次\n- 專科: 兒科\n\n**Output**:\n- `17022B.cql` - With age check, frequency check, and pediatric specialty check\n- `2.16.840.1.113762.1.4.1287.6.json` - Uses `descendent-of` filter for J45 (asthma)\n\n### Example 3: Multiple Subpopulations (12216C)\n\n**Input**:\n- Rule ID: 12216C\n- 點數: 900點\n- 適應症1: C型肝炎抗體陽性之HIV感染者、靜脈注射藥癮者 (每一年限一次)\n- 適應症2: C型肝炎抗體陽性之慢性血液透析病人 (每四年限一次)\n\n**Output**:\n- `12216C.cql` - With subpopulation 1 and 2, different frequency rules\n- `2.16.840.1.113762.1.4.1287.[N].json` - HIV codes with appropriate filters\n- `2.16.840.1.113762.1.4.1287.[N+1].json` - Dialysis dependency codes\n\n## Important Rules\n\n1. **Never create new codesystem URLs** - Only use the eight approved URLs\n2. **Never deviate from standard structure** - Follow examples exactly\n3. **Always include all helper functions** - Even if not directly used\n4. **CQL and ValueSet URLs must match** - This is absolutely critical\n5. **Use patterns, don't innovate** - Combine existing patterns for new scenarios\n6. **Chinese in variable names is OK** - This is standard practice\n7. **Preserve exact indentation** - 2 spaces, no tabs\n\n## Triggering Keywords\n\nActivate when user mentions:\n- NHI CQL, 健保 CQL\n- 健保給付規則, 給付審查, 藥品審查\n- CQL Library, 健保 ValueSet, 健保代碼\n- Taiwan health insurance reimbursement\n- Generate CQL for [rule code]\n\n## Notes\n\n- GT\u002F folder was used for learning only - **not available at runtime**\n- All knowledge must come from patterns in this SKILL.md\n- When uncertain, combine documented patterns rather than improvising\n- 中文 and English 混用 is standard in NHI CQL (both in variable names and comments)\n\n### Critical ValueSet URL Pattern Difference\n\n**In ValueSet JSON** (url field):\n```json\n\"url\": \"http:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.6\"\n```\nUses `http:\u002F\u002F` (no 's')\n\n**In CQL** (valueset declaration):\n```cql\nvalueset \"name\": 'https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.6'\n```\nUses `https:\u002F\u002F` (with 's')\n\nThis is intentional and follows GT examples exactly.\n\n### ValueSet File Naming\n\n- File name = Full OID: `2.16.840.1.113762.1.4.1287.6.json`\n- NOT descriptive names like `17022B-indications.json`\n- id field in JSON = file name without .json extension\n","# NHI CQL Generator\n\nGenerate CQL Library (.cql) and FHIR ValueSet (.json) files from Taiwan NHI reimbursement rules text.\n\n## Overview\n\nThis skill generates standardized clinical decision support artifacts for Taiwan's National Health Insurance system:\n1. **CQL Library** - Clinical Quality Language for payment審查邏輯\n2. **FHIR ValueSet** - Code sets (適應症, 禁忌症, 藥品, etc.)\n3. **Dependency Libraries** - Required CQL libraries that must accompany every generated CQL file\n\n**Critical**: All patterns are learned from 50+ GT examples. Do NOT deviate from documented patterns.\n\n### Required Dependency Libraries\n\nEvery generated CQL file depends on two shared libraries located in `.github\u002Fskills\u002Fnhi-cql-generator\u002Fassets\u002F`:\n\n1. **FHIRHelpers.cql** (version 4.0.1)\n   - Provides FHIR data model interaction helpers\n   - Converts FHIR types to CQL types\n   - Required by all FHIR-based CQL libraries\n\n2. **CDSConnectCommonsForFHIRv401.cql** (version 2.1.0, aliased as C3F)\n   - Provides common clinical decision support functions that can be used directly\n   - **Frequently used functions**:\n     * `C3F.Confirmed(Conditions)` - Filter confirmed conditions\n     * `C3F.Verified(Observations)` - Filter verified observations  \n     * `C3F.MostRecent(Observations)` - Get most recent observation\n     * `C3F.QuantityValue(Observation)` - Extract quantity value\n     * `C3F.ObservationLookBack(Observations, LookBack)` - Observations in time window\n     * `C3F.MostRecentProcedure(Procedures)` - Get most recent procedure\n     * `C3F.ActiveCondition(Conditions)` - Filter active conditions\n     * `C3F.PeriodToInterval(Period)` - Convert FHIR Period to CQL Interval\n   - **Usage**: Directly use C3F functions with the `C3F.` prefix (e.g., `C3F.Confirmed([Condition: \"code\"])`)\n   - **Note**: GT examples redundantly redefine these functions, but this is unnecessary - you should use C3F functions directly\n\n**IMPORTANT**: When generating CQL artifacts, you MUST copy these two files to the output directory alongside the generated `.cql` files. Without them, the CQL will fail with error:\n```\nCould not load source for library CDSConnectCommonsForFHIRv401, version 2.1.0, namespace uri null.\n```\n\n## CQL Structure Patterns\n\n### Library Declaration\n\n```cql\nlibrary \"[規則編號]\" version '0.0.1'\n```\n\n- **Library name**: Exact rule code (e.g., \"08111B\", \"12216C\", \"69041B\")\n- **Version**: Always `'0.0.1'`\n\n### Standard Headers (Fixed Order)\n\n```cql\nlibrary \"[規則編號]\" version '0.0.1'\n\nusing FHIR version '4.0.1'\n\ninclude \"FHIRHelpers\" version '4.0.1' called FHIRHelpers\ninclude \"CDSConnectCommonsForFHIRv401\" version '2.1.0' called C3F\n```\n\n**Never change**: FHIR version, FHIRHelpers version, C3F version, or aliases.\n\n### ValueSet Declarations\n\nAfter include statements, before codesystem declarations:\n\n```cql\nvalueset \"[中文名稱] valueset\": '[ValueSet URL]'\n```\n\n**URL Pattern**: `https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.[sequential-number]`\n\n**Examples**:\n- `valueset \"17022B 呼氣一氧化氮監測(FeNO) valueset\": 'https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.6'`\n- `valueset \"糖尿病合併慢性腎病變 valueset\": 'https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.46'`\n\n### CodeSystem URLs (Complete Approved List)\n\nUse **ONLY** these codesystem URLs:\n\n```cql\ncodesystem \"ICD-10-CM\": 'http:\u002F\u002Fhl7.org\u002Ffhir\u002Fsid\u002Ficd-10-cm'\ncodesystem \"ICD-10-PCS\": 'http:\u002F\u002Fwww.cms.gov\u002FMedicare\u002FCoding\u002FICD10'\ncodesystem \"LOINC\": 'http:\u002F\u002Floinc.org'\ncodesystem \"SCT\": 'http:\u002F\u002Fsnomed.info\u002Fsct'\ncodesystem \"TWMedicalServicePayment\": 'https:\u002F\u002Ftwcore.mohw.gov.tw\u002Fig\u002Ftwcore\u002FCodeSystem\u002Fmedical-service-payment-tw'\ncodesystem \"CONDVERSTATUS\": 'http:\u002F\u002Fterminology.hl7.org\u002FCodeSystem\u002Fcondition-ver-status'\ncodesystem \"CONDCLINSTATUS\": 'http:\u002F\u002Fterminology.hl7.org\u002FCodeSystem\u002Fcondition-clinical'\ncodesystem \"ActCode\": 'http:\u002F\u002Fterminology.hl7.org\u002FCodeSystem\u002Fv3-ActCode'\n```\n\n### Context Declaration\n\n```cql\ncontext Patient\n```\n\nAlways use `Patient` context.\n\n### Define Statements Pattern\n\n**Standard structure** observed in all examples:\n\n```cql\ndefine \"[適應症或條件名稱]\":\n  exists ( C3F.Confirmed([Condition: \"[valueset名稱]\"]) )\n\ndefine \"MeetsInclusionCriteria\":\n  \"[主要適應症]\"\n  \ndefine \"InPopulation\":\n  \"MeetsInclusionCriteria\"\n\ndefine \"Recommendation\":\n  if \"InPopulation\" then '健保給付[點數]點' \n    else null\n\ndefine \"Rationale\":\n  null\n\ndefine \"Links\":\n  null\n\ndefine \"Suggestions\":\n  null\n\ndefine \"Errors\":\n  null\n```\n\n### Using C3F Helper Functions\n\n**Direct Usage** - Use C3F library functions directly without redefining them:\n\n```cql\n\u002F\u002F ✅ Correct: Use C3F functions directly\ndefine \"適應症\":\n  exists ( C3F.Confirmed([Condition: \"適應症 valueset\"]) )\n\ndefine \"Recent Observations\":\n  C3F.ObservationLookBack([Observation: \"code\"], 1 year)\n\ndefine \"Lab Value\":\n  C3F.QuantityValue( C3F.MostRecent([Observation: \"code\"]) )\n```\n\n**Common C3F Functions**:\n- `C3F.Confirmed(Conditions)` - Filters to confirmed conditions (verificationStatus = 'confirmed')\n- `C3F.Verified(Observations)` - Filters to verified observations (status = 'final', 'corrected', or 'amended')\n- `C3F.ObservationLookBack(Observations, LookBack)` - Observations within time window\n- `C3F.MostRecent(Observations)` - Most recent observation by effective date\n- `C3F.QuantityValue(Observation)` - Extract quantity value from observation\n- `C3F.MostRecentProcedure(Procedures)` - Most recent procedure\n- `C3F.ActiveCondition(Conditions)` - Active conditions (clinicalStatus = 'active', no abatement)\n- `C3F.PeriodToInterval(Period)` - Convert FHIR Period to CQL Interval\n\n**Note**: GT examples redundantly redefine these functions at the end of each file, but this is **unnecessary duplication**. Simply use `C3F.FunctionName()` directly.\n\n## Common Logic Patterns\n\n### Condition Checking\n\n```cql\nexists ( C3F.Confirmed([Condition: \"[valueset名稱]\"]) )\n```\n\n### Multiple Conditions (OR)\n\n```cql\nexists ( C3F.Confirmed([Condition: \"valueset1\"])\n    union C3F.Confirmed([Condition: \"valueset2\"])\n)\n```\n\n### Multiple Conditions (AND)\n\n```cql\n\"condition1\" and \"condition2\"\n```\n\n### Observation with Time Window\n\n```cql\nCount(C3F.ObservationLookBack([Observation: \"[code]\"], 1 year)) \u003C 3\n```\n\n### Age Checking\n\n```cql\nAgeInYears() >= 6 and AgeInYears() \u003C 13\n```\n\n### Encounter with Specialty\n\n```cql\n[Encounter: \"[valueset]\"] E\n  where ( E.serviceType ~ \"[specialty code]\" )\n```\n\n### Procedure Lookback (using C3F)\n\n```cql\nC3F.ProcedureLookBack([Procedure: \"[code]\"], 6 months)\n```\n\n### Nested Conditionals (for複雜給付條件)\n\n```cql\ndefine \"Recommendation\":\n  if \"condition1\" then if \"condition2\" then '說明A'\n    else '說明B'\n  else if \"condition3\" then '說明C'\n  else null\n```\n\n### Subpopulations Pattern\n\nFor rules with multiple適應症 with different頻率:\n\n```cql\ndefine \"subpopulation 1\":\n  if \"InPopulation\" is not true then null \n    else [specific condition for subpop1]\n\ndefine \"subpopulation 2\":\n  if \"InPopulation\" is not true then null \n    else [specific condition for subpop2]\n    \ndefine \"Recommendation\":\n  if \"subpopulation 1\" then '健保給付[點數]點，[規範1]'\n  else if \"subpopulation 2\" then '健保給付[點數]點，[規範2]'\n  else null\n```\n\n## Medical Knowledge Mapping\n\n### Spinal Disorders Coding\n\nWhen rules mention \"脊髓損傷或病變\", include **ALL** three categories:\n\n| Category | ICD-10-CM | Examples |\n|----------|-----------|----------|\n| **Trauma** | S14.*, S24.*, S34.*, S44.* | Spinal cord injury |\n| **Disease** | G95.*, G82.* | Spinal cord disorders, paraplegia |\n| **Degeneration** | M43.3, M47.1, M50.0, M51.0 | Spondylolisthesis, myelopathy, disc disorders |\n\n**Critical**: \"病變\" includes both functional disease (G-codes) AND degenerative structural changes (M-codes).\n\n### Stroke Sequelae Coding\n\nFor \"腦中風後遺症\" or \"中風導致之肢體偏癱\":\n\n| Scope | ICD-10-CM | Purpose |\n|-------|-----------|---------|\n| **General stroke** | I69.* | All stroke sequelae |\n| **Hemiplegia types** | I69.33-I69.35 | Dominant\u002Fnon-dominant\u002Funspecified side |\n| **Specific sequelae** | I69.3, I69.33, I69.34, I69.35, I69.39 | Cerebral infarction aftereffects |\n\n**Pattern**: Use I69.* for broad inclusion, add specific I69.3X codes when hemiplegia is explicitly mentioned.\n\n### Peripheral Neuropathy\n\nFor \"周邊神經病變\":\n\n- **Diabetic**: E11.4* (Type 2 DM with neurological complications)\n- **General**: G62.* (polyneuropathy), G63.* (neuropathy in diseases)\n- **Specific**: G62.9 (unspecified polyneuropathy)\n\n### Observation Value Checking Pattern\n\nFor laboratory or measurement constraints:\n\n```cql\ndefine \"低密度脂蛋白膽固醇異常\":\n  exists (\n    [Observation: \"LOINC code 18262-6\"] O\n      where O.value as Quantity > 100 'mg\u002FdL'\n        and O.status = 'final'\n  )\n```\n\n### Complex Age Range Checks\n\nFor rules specifying age ranges with measurement timing:\n\n```cql\ndefine \"符合年齡條件\":\n  ( AgeInYears() >= 10 and AgeInYears() \u003C= 17 )\n    or ( AgeInYears() >= 6 and AgeInYears() \u003C 10 and \"已測量過基線值\" )\n```\n\n## Code Style Rules\n\n- **Indentation**: 2 spaces (NO tabs)\n- **String quotes**: Single quotes `'...'` for all strings\n- **Line breaks**: Blank line between major sections (valuesets, codesystems, context, defines)\n- **Comments**: Use `\u002F\u002F` sparingly, written in Chinese when explaining業務邏輯\n- **Naming**: Chinese variable names permitted (e.g., `define \"氣喘\":`, `define \"懷孕糖尿病人、妊娠糖尿病人\":`)\n- **Boolean checks**: Use `\"variable\"` not `\"variable\" = true`\n\n## NHI Rule Text Parsing\n\n### Rule ID Format\n\nPattern: `[數字]{2,5}[字母]` (e.g., 08111B, 12216C, 69041B, 83102K)\n\n### Common Phrases to Extract\n\n**適應症 (Indications)**:\n- \"適應症：\", \"適應症包括：\"\n- \"限...使用\", \"限...申報\"\n- \"適用於...\", \"符合...\"\n\n**禁忌症 (Contraindications)**:\n- \"禁忌症：\", \"不得用於...\"\n- \"排除...\", \"不適用\"\n\n**支付規範 (Payment Rules)**:\n- \"支付規範：\", \"執行頻率：\"\n- \"每[時間]限申報[次數]次\"\n- \"一年限申報[數字]次\"\n- \"不得同時申報...\"\n\n**點數 (Points)**:\n- \"[數字]點\" (e.g., \"800點\", \"17350點\")\n\n**專科限制 (Specialty)**:\n- \"限...專科醫師\", \"限由...執行\"\n\n### Diagnosis Code Extraction\n\nFrom text patterns like:\n- \"多發性硬化症、運動神經元疾病、脊髓損傷...\" → Create valueset for ICD-10-CM codes\n- \"四肢自體動脈粥樣硬化（I70.2～I70.7）\" → Code range with all subcodes\n- \"糖尿病酮酸中毒\" → Look up ICD-10-CM code\n\n### Frequency Constraints Encoding\n\n**CRITICAL**: Always filter by the **specific NHI procedure code** using `TWMedicalServicePayment` codesystem. NEVER use bare `[Procedure]` (this would match ALL procedures, not the one being regulated).\n\n#### Required: Declare procedure code at top of file\n\n```cql\ncodesystem \"TWMedicalServicePayment\": 'https:\u002F\u002Ftwcore.mohw.gov.tw\u002Fig\u002Ftwcore\u002FCodeSystem\u002Fmedical-service-payment-tw'\n\ncode \"[代號] 健保給付代碼\": '[代號]' from \"TWMedicalServicePayment\" display '[項目名稱]'\n```\n\n#### Frequency check pattern\n\n```cql\n\u002F\u002F ✅ Correct: counts only THIS specific procedure\ndefine \"頻率符合\":\n  Count(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 1 year)) \u003C N\n\n\u002F\u002F ❌ WRONG: counts ALL procedures in the patient's history\ndefine \"頻率符合\":\n  Count(C3F.ProcedureLookBack([Procedure], 1 year)) \u003C N\n```\n\n| Rule Text | CQL Encoding |\n|-----------|--------------|\n| \"一年限申報三次\" | `Count(ObservationLookBack([Observation: ...], 1 year)) \u003C 3` |\n| \"每四年限申報一次\" | `Count(ObservationLookBack([Observation: ...], 4 years)) \u003C 1` |\n| \"每人以申報一次為原則\" | Track across patient lifetime |\n| \"每次就診...每次治療應間隔至少一週\" | Date diff checking |\n| \"一年限申報三次\" | `Count(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 1 year)) \u003C 3` |\n| \"每四年限申報一次\" | `Count(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 4 years)) \u003C 1` |\n| \"每人以申報一次為原則\" | `not exists(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 100 years))` |\n| \"每週最多N次\" | `Count(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 7 days)) \u003C N` |\n| \"每月限一次\" | `Count(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 30 days)) \u003C 1` |\n\n#### Per-Encounter \u002F Per-Hospitalization check\n\nWhen the rule says **\"限住院期間申報一次\"** or **\"同一就診申報一次\"**, use Encounter reference instead of a time window. A time window (e.g., \"1 year\") would incorrectly block re-admission for a new event.\n\n```cql\n\u002F\u002F 取得目前就醫 Encounter（最近一次進行中或完成的）\ndefine \"目前住院Encounter\":\n  Last(\n    [Encounter] E\n      where E.status = 'in-progress' or E.status = 'finished'\n      sort by start of period\n  )\n\n\u002F\u002F 本次住院期間尚未申報過本項目\ndefine \"本次住院未申報過\":\n  \"目前住院Encounter\" is not null\n    and not exists(\n      [Procedure: \"[代號] 健保給付代碼\"] P\n        where P.encounter.reference = 'Encounter\u002F' + \"目前住院Encounter\".id\n    )\n```\n\n#### \"同一治療期間\" (Episode of Care) check\n\nWhen rule says **\"同一治療期間至多N次\"**, the ideal boundary is `EpisodeOfCare`. As a pragmatic approximation, use Encounter-reference for the per-visit part, and ProcedureLookBack with a reasonable lookback window for the total-count part:\n\n```cql\ndefine \"本次就診未申報\":\n  \"目前住院Encounter\" is not null\n    and not exists(\n      [Procedure: \"[代號] 健保給付代碼\"] P\n        where P.encounter.reference = 'Encounter\u002F' + \"目前住院Encounter\".id\n    )\n\n\u002F\u002F 治療期間總次數：以 1 年作為最長治療期間的保守估計\ndefine \"治療期間總次數符合\":\n  Count(C3F.ProcedureLookBack([Procedure: \"[代號] 健保給付代碼\"], 1 year)) \u003C N\n```\n\n> **Note**: The ideal approach for \"同一治療期間\" is to use `EpisodeOfCare`, but this requires the FHIR server to populate `EpisodeOfCare` resources. The time-window approximation is the practical fallback.\n\n### Other Regulation Handling (其他規範處理)\n\n**Critical**: Distinguish between **pre-authorization criteria** (事前資格檢查) and **post-payment rules** (事後支付規則).\n\n#### Type 1: Pre-Authorization Criteria → Convert to CQL Logic\n\nThese MUST be encoded as executable logic in MeetsInclusionCriteria:\n\n**Pattern: Contraindication** (\"禁忌症：...\")\n\nWhen a rule lists contraindications, create a **separate contraindication ValueSet** and check for absence:\n\n```cql\n\u002F\u002F 1. Declare a separate contraindication valueset\nvalueset \"[代號] 禁忌症\": 'https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.[n]'\n\n\u002F\u002F 2. Define the contraindication check\ndefine \"有禁忌症\":\n  exists ( C3F.Confirmed([Condition: \"[代號] 禁忌症\"]) )\n\n\u002F\u002F 3. Incorporate into MeetsInclusionCriteria\ndefine \"MeetsInclusionCriteria\":\n  \"Has Indication\" and not \"有禁忌症\"\n\n\u002F\u002F 4. Recommendation branches (always check indication first → then contraindication)\ndefine \"Recommendation\":\n  if not \"Has Indication\" then null\n    else if \"有禁忌症\" then '不得申報。病患符合禁忌症：[詳細原因]。'\n    else '健保給付。...'\n```\n\n**Important**: The contraindication JSON file uses the same structure as the indication ValueSet. Give it a **distinct OID number** (e.g., indication = `.9`, contraindication = `.200`).\n\n**Pattern: Specialist Restriction** (\"限...專科醫師執行\")\n\n```cql\ncodesystem \"SCT\": 'http:\u002F\u002Fsnomed.info\u002Fsct'\n\ncode \"Specialist code\": '[SNOMED-code]' from \"SCT\" display '[specialist-type]'\n\ndefine \"performer_id\":\n  Last(Split(First(\"RecentProcedure\".performer).actor.reference, '\u002F'))\n\ndefine \"Performer_ref\":\n  [Practitioner] P where P.id = \"performer_id\"\n\ndefine \"Qualified_Practitioner\":\n  exists ( \"Performer_ref\".qualification q\n    where q.code ~ \"Specialist code\" )\n\ndefine \"MeetsInclusionCriteria\":\n  \"[適應症]\" and \"Qualified_Practitioner\"\n```\n\n**Examples**:\n- \"限外科專科醫師執行\" → SNOMED CT: 224555008 (Vascular surgeon)\n- \"限兒科專科\" → SNOMED CT: 24251000087109 (General pediatric specialty)\n- \"限心臟血管外科\" → SNOMED CT: 309296001 (Cardiac surgeon)\n\n**Pattern: Procedure Type Restriction**\n\nWhen rule specifies specific surgical procedures:\n\n```cql\ncodesystem \"ICD-10-PCS\": 'http:\u002F\u002Fwww.cms.gov\u002FMedicare\u002FCoding\u002FICD10'\n\ncode \"Procedure1 code\": '[code]' from \"ICD-10-PCS\" display '[description]'\ncode \"Procedure2 code\": '[code]' from \"ICD-10-PCS\" display '[description]'\n\ndefine \"ApplicableProcedure\":\n  C3F.MostRecentProcedure ( [Procedure: \"Procedure1 code\"]\n    union [Procedure: \"Procedure2 code\"]\n  )\n\ndefine \"MeetsInclusionCriteria\":\n  \"[適應症]\" and exists(\"ApplicableProcedure\")\n```\n\n**Pattern: Encounter Specialty Check**\n\nFor rules limiting to specific clinical departments:\n\n```cql\ncode \"Department specialty code\": '[SNOMED-code]' from \"SCT\" display '[specialty]'\n\ndefine \"SpecialtyEncounter\":\n  [Encounter] E where E.serviceType ~ \"Department specialty code\"\n\ndefine \"encounter check\":\n  exists(\"SpecialtyEncounter\")\n\ndefine \"Recommendation\":\n  if \"InPopulation\" is not true then null\n    else if \"encounter check\" then '給付'\n    else '非[科別]申報，不予給付'\n```\n\n#### Type 2: Post-Payment Rules → Include in Recommendation Text Only\n\nThese should appear in Recommendation string but NOT in MeetsInclusionCriteria:\n\n**Examples**:\n- \"一般材料費得另加計百分之五十\" → Include in Recommendation only\n- \"應事先申請\" → Include in Recommendation only\n- \"需檢附...報告\" → Include in Recommendation only\n- \"不得同時申報...\" → Include in Recommendation as note\n\n**Pattern**:\n```cql\ndefine \"Recommendation\":\n  if \"InPopulation\" then '健保給付[點數]點，[描述]，一般材料費得另加計百分之五十'\n  else null\n```\n\n#### Decision Logic: When to Convert to CQL vs Text Only\n\n| Phrase Pattern | Type | Action |\n|---------------|------|--------|\n| 限...專科醫師執行 | Pre-auth | ✅ Convert to Practitioner.qualification check |\n| 限...科別申報 | Pre-auth | ✅ Convert to Encounter.serviceType check |\n| 限特定手術類型 | Pre-auth | ✅ Convert to Procedure code check |\n| 材料費加計...% | Post-payment | ❌ Text only in Recommendation |\n| 應事先申請 | Administrative | ❌ Text only in Recommendation |\n| 需檢附報告 | Administrative | ❌ Text only in Recommendation |\n\n**Critical Rule**: If the regulation affects **whether payment is approved**, it's pre-authorization → convert to CQL. If it only affects **how much** or **when** to pay, it's post-payment → text only.\n\n## ValueSet Generation\n\n### ValueSet JSON Template\n\nBased on GT examples, use this complete structure:\n\n```json\n{\n  \"resourceType\": \"ValueSet\",\n  \"id\": \"2.16.840.1.113762.1.4.1287.[number]\",\n  \"meta\": {\n    \"versionId\": \"1\",\n    \"lastUpdated\": \"[timestamp]\",\n    \"profile\": [\n      \"http:\u002F\u002Fhl7.org\u002Ffhir\u002FStructureDefinition\u002Fshareablevalueset\",\n      \"http:\u002F\u002Fhl7.org\u002Ffhir\u002Fus\u002Fcqfmeasures\u002FStructureDefinition\u002Fcomputable-valueset-cqfm\",\n      \"http:\u002F\u002Fhl7.org\u002Ffhir\u002Fus\u002Fcqfmeasures\u002FStructureDefinition\u002Fpublishable-valueset-cqfm\"\n    ]\n  },\n  \"extension\": [\n    {\n      \"url\": \"http:\u002F\u002Fhl7.org\u002Ffhir\u002FStructureDefinition\u002Fvalueset-author\",\n      \"valueContactDetail\": {\n        \"name\": \"Industrial Technology Research Institute Author\"\n      }\n    },\n    {\n      \"url\": \"http:\u002F\u002Fhl7.org\u002Ffhir\u002FStructureDefinition\u002Fresource-lastReviewDate\",\n      \"valueDate\": \"[YYYY-MM-DD]\"\n    },\n    {\n      \"url\": \"http:\u002F\u002Fhl7.org\u002Ffhir\u002FStructureDefinition\u002Fvalueset-effectiveDate\",\n      \"valueDate\": \"[YYYY-MM-DD]\"\n    }\n  ],\n  \"url\": \"http:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.[number]\",\n  \"identifier\": [\n    {\n      \"system\": \"urn:ietf:rfc:3986\",\n      \"value\": \"urn:oid:2.16.840.1.113762.1.4.1287.[number]\"\n    }\n  ],\n  \"version\": \"[YYYYMMDD]\",\n  \"name\": \"[EnglishCamelCaseName]\",\n  \"title\": \"[English title or Chinese title]\",\n  \"status\": \"active\",\n  \"date\": \"[timestamp]\",\n  \"publisher\": \"Industrial Technology Research Institute Steward\",\n  \"description\": \"[規則編號，可多個用逗號分隔如 63007B, 63008B]\",\n  \"jurisdiction\": [\n    {\n      \"extension\": [\n        {\n          \"url\": \"http:\u002F\u002Fhl7.org\u002Ffhir\u002FStructureDefinition\u002Fdata-absent-reason\",\n          \"valueCode\": \"unknown\"\n        }\n      ]\n    }\n  ],\n  \"purpose\": \"(Clinical Focus: ...),(Data Element Scope: ...),(Inclusion Criteria: ...),(Exclusion Criteria: ...)\",\n  \"compose\": {\n    \"include\": [\n      {\n        \"system\": \"[CodeSystem URL]\",\n        \"version\": \"2025\",\n        \"filter\": [\n          {\n            \"property\": \"concept\",\n            \"op\": \"[operator]\",\n            \"value\": \"[code]\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### ID Naming Convention\n\nPattern: `2.16.840.1.113762.1.4.1287.[sequential-number]`\n\nThe ID is the **full OID**, not a custom name. File name matches the ID:\n- File: `2.16.840.1.113762.1.4.1287.6.json`\n- ID: `\"2.16.840.1.113762.1.4.1287.6\"`\n\n### URL Pattern\n\n**Critical**: Use `http:\u002F\u002F` (NOT `https:\u002F\u002F`) in url field:\n```json\n\"url\": \"http:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.[number]\"\n```\n\n**In CQL**: Use `https:\u002F\u002F` in valueset declarations:\n```cql\nvalueset \"name\": 'https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.[number]'\n```\n\n### Filter Operators (from GT examples)\n\nUse `filter` instead of explicit `concept` array:\n\n**Common operators**:\n- `\"op\": \"descendent-of\"` - Include code and all descendants (most common)\n- `\"op\": \"is-a\"` - Include code and descendants\n- `\"op\": \"=\"` - Exact match single code\n- `\"op\": \"in\"` - Multiple codes (comma-separated in value)\n\n**Examples**:\n```json\n\u002F\u002F All J45.* asthma codes\n{\"property\": \"concept\", \"op\": \"descendent-of\", \"value\": \"J45\"}\n\n\u002F\u002F Specific codes\n{\"property\": \"concept\", \"op\": \"=\", \"value\": \"C79.81\"}\n\n\u002F\u002F Multiple specific codes\n{\"property\": \"concept\", \"op\": \"in\", \"value\": \"E10.22,E13.22,E08.22\"}\n```\n\n### Filter Operator Selection Strategy\n\nChoose operator based on code specificity and clinical intent:\n\n| Operator | Use When | ICD-10 Code Pattern | Example |\n|----------|----------|---------------------|---------|\n| **`=`** | Exact leaf code needed | 6-7 digits (e.g., G62.9, I69.398) | Single specific diagnosis |\n| **`is-a`** | Mid-level category | 4-5 digits (e.g., J45.5, E11.4) | Specific subtype with few children |\n| **`descendent-of`** | Broad family inclusion | 3-4 digits (e.g., J45, I69, G62) | All variants needed |\n| **`in`** | Multiple unrelated codes | Mixed | Enumerate disparate codes |\n\n**Code Granularity Guidelines**:\n- **Preferred**: Mid-level codes (5-6 digits) - balance precision and coverage\n- **Avoid**: Too broad (3 digits: J45 vs J45.*) or too narrow (7+ digits)\n- **Quick judgment**: Code length 3-4 → descendent-of; 5-6 → is-a; 7+ → =\n\n**Real Examples from GT**:\n```json\n\u002F\u002F G62.9 (7 digits, leaf code) - use exact match\n{\"property\": \"concept\", \"op\": \"=\", \"value\": \"G62.9\"}\n\n\u002F\u002F E11.4 (5 digits, mid-level) - use is-a\n{\"property\": \"concept\", \"op\": \"is-a\", \"value\": \"E11.4\"}\n\n\u002F\u002F I69 (3 digits, broad family) - use descendent-of\n{\"property\": \"concept\", \"op\": \"descendent-of\", \"value\": \"I69\"}\n\n\u002F\u002F Multiple unrelated codes - use in\n{\"property\": \"concept\", \"op\": \"in\", \"value\": \"M43.3,M47.1,M50.0,M51.0\"}\n```\n\n**Decision Logic**:\n1. If code explicitly ends with .0, .9, or has 6+ digits → `=`\n2. If code has 4-5 digits and represents specific subtype → `is-a`\n3. If code is 3-4 digits and needs all variants → `descendent-of`\n4. If multiple disparate codes listed → `in`\n\n### Purpose Field Format\n\nStandard 4-part structure (observed in all GT examples):\n\n```\n(Clinical Focus: [臨床焦點]),(Data Element Scope: [資料元素範圍]),(Inclusion Criteria: [納入條件]),(Exclusion Criteria: [排除條件，若無則寫 No])\n```\n\n**Critical**: ValueSet.url in JSON **must exactly match** the valueset declaration URL in CQL (except http vs https).\n\n### Common ValueSet Types\n\n1. **Diagnosis codes** (ICD-10-CM) - Most common\n   - System: `http:\u002F\u002Fhl7.org\u002Ffhir\u002Fsid\u002Ficd-10-cm`\n   - Version: `\"2025\"`\n   - Use filters, not explicit concept lists\n2. **Procedure codes** (ICD-10-PCS or TWMedicalServicePayment)\n   - System: `http:\u002F\u002Fwww.cms.gov\u002FMedicare\u002FCoding\u002FICD10` or `https:\u002F\u002Ftwcore.mohw.gov.tw\u002Fig\u002Ftwcore\u002FCodeSystem\u002Fmedical-service-payment-tw`\n3. **Lab tests** (LOINC)\n   - System: `http:\u002F\u002Floinc.org`\n4. **Clinical findings** (SNOMED CT)\n   - System: `http:\u002F\u002Fsnomed.info\u002Fsct`\n\n### Multiple Rules Sharing Same ValueSet\n\nFrom GT examples, one ValueSet may support multiple rules:\n- `\"description\": \"63007B, 63008B\"` - Modified radical mastectomy (single\u002Fbilateral)\n- `\"description\": \"13030B,13031B,13032B\"` - Different H. pylori tests\n\nWhen rules share indications, use the same ValueSet ID.\n\n## Workflow\n\n### Step 1: Collect Input\n\nAsk user for:\n- **規則編號** (Rule ID) - e.g., \"08111B\"\n- **完整給付規則文字** (Full rule text including適應症, 禁忌症, 支付規範, 點數)\n\n### Step 2: Parse Rule Text\n\nExtract and identify:\n- Rule ID\n- 點數 (reimbursement points)\n- 適應症 (indications) - list of diagnoses\u002Fconditions\n- 禁忌症 (contraindications) - if any\n- 執行頻率限制 (frequency limits)\n- 不得同時申報項目 (cannot claim with)\n- 專科限制 (specialty restrictions)\n- 其他支付規範 (other payment rules)\n\n### Step 3: Generate ValueSets\n\nFor **each distinct code set** identified:\n\n1. Create JSON file: `2.16.840.1.113762.1.4.1287.[number].json`\n2. Use complete template structure from GT examples\n3. Assign sequential OID number\n4. Set url with `http:\u002F\u002F` (NOT https)\n5. Populate filter operators based on code patterns:\n   - Use `descendent-of` for code families (e.g., J45 for all asthma)\n   - Use `in` for multiple specific codes\n   - Use `=` for single specific codes\n6. Fill purpose field with 4-part structure\n7. Save with UTF-8 encoding\n\n**Important**: \n- File name = full OID (e.g., `2.16.840.1.113762.1.4.1287.6.json`)\n- url field uses `http:\u002F\u002F` \n- CQL valueset declaration uses `https:\u002F\u002F`\n\n### Step 4: Generate CQL Library\n\nFollowing exact structure:\n\n1. Library declaration with rule ID\n2. using FHIR version\n3. include statements (FHIRHelpers, C3F)\n4. valueset declarations (URLs must match JSON files)\n5. codesystem declarations\n6. Standard code\u002Fconcept for Confirmed\n7. context Patient\n8. define statements (適應症, conditions, InPopulation, Recommendation, etc.)\n9. Standard define statements (Rationale, Links, Suggestions, Errors as null)\n10. All five helper functions\n\n### Step 5: Validate Generated Files\n\nChecklist:\n\n- ✓ CQL valueset declaration URLs **exactly match** ValueSet JSON url fields\n- ✓ Only codesystem URLs from approved list used\n- ✓ All five helper functions included at end\n- ✓ Structure follows examples (headers, blank lines, 2-space indentation)\n- ✓ Recommendation includes 點數 and key給付規範\n- ✓ File encoding is UTF-8\n- ✓ No tabs, only spaces\n\n### Step 6: Provide Output\n\nDeliver to user:\n\n1. **CQL file**: `[規則編號].cql` (plain text)\n2. **ValueSet file(s)**: One or more `2.16.840.1.113762.1.4.1287.[number].json` files\n3. **Dependency libraries**: Copy from `.github\u002Fskills\u002Fnhi-cql-generator\u002Fassets\u002F` to output directory:\n   - `FHIRHelpers.cql`\n   - `CDSConnectCommonsForFHIRv401.cql`\n4. **Mapping table**: \n\n```markdown\n| CQL ValueSet Declaration | ValueSet File | URL (CQL uses https, JSON uses http) |\n|--------------------------|---------------|---------------------------------------|\n| [中文名稱] valueset | 2.16.840.1.113762.1.4.1287.[N].json | https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.[N] |\n```\n\n5. **Validation report**: Confirm all patterns followed ✓\n\n**Critical**: The CQL file will NOT execute without the dependency libraries in the same directory. Always include them in the output.\n\n## Examples\n\n### Example 1: Simple Rule (08111B)\n\n**Input**: \n- Rule ID: 08111B\n- 點數: 800點\n- 適應症: 凝血異常，疑有Von-willebrands disease者\n\n**Output**:\n- `08111B.cql` - With Von Willebrand disease codes\n- `2.16.840.1.113762.1.4.1287.1.json` - ICD-10-CM codes with filter for VWD codes\n\n### Example 2: Rule with Frequency (17022B)\n\n**Input**:\n- Rule ID: 17022B\n- 點數: 748點  \n- 適應症: 六歲以上至未滿十三歲確診氣喘患者追蹤使用\n- 頻率: 一年最多申報三次\n- 專科: 兒科\n\n**Output**:\n- `17022B.cql` - With age check, frequency check, and pediatric specialty check\n- `2.16.840.1.113762.1.4.1287.6.json` - Uses `descendent-of` filter for J45 (asthma)\n\n### Example 3: Multiple Subpopulations (12216C)\n\n**Input**:\n- Rule ID: 12216C\n- 點數: 900點\n- 適應症1: C型肝炎抗體陽性之HIV感染者、靜脈注射藥癮者 (每一年限一次)\n- 適應症2: C型肝炎抗體陽性之慢性血液透析病人 (每四年限一次)\n\n**Output**:\n- `12216C.cql` - With subpopulation 1 and 2, different frequency rules\n- `2.16.840.1.113762.1.4.1287.[N].json` - HIV codes with appropriate filters\n- `2.16.840.1.113762.1.4.1287.[N+1].json` - Dialysis dependency codes\n\n## Important Rules\n\n1. **Never create new codesystem URLs** - Only use the eight approved URLs\n2. **Never deviate from standard structure** - Follow examples exactly\n3. **Always include all helper functions** - Even if not directly used\n4. **CQL and ValueSet URLs must match** - This is absolutely critical\n5. **Use patterns, don't innovate** - Combine existing patterns for new scenarios\n6. **Chinese in variable names is OK** - This is standard practice\n7. **Preserve exact indentation** - 2 spaces, no tabs\n\n## Triggering Keywords\n\nActivate when user mentions:\n- NHI CQL, 健保 CQL\n- 健保給付規則, 給付審查, 藥品審查\n- CQL Library, 健保 ValueSet, 健保代碼\n- Taiwan health insurance reimbursement\n- Generate CQL for [rule code]\n\n## Notes\n\n- GT\u002F folder was used for learning only - **not available at runtime**\n- All knowledge must come from patterns in this SKILL.md\n- When uncertain, combine documented patterns rather than improvising\n- 中文 and English 混用 is standard in NHI CQL (both in variable names and comments)\n\n### Critical ValueSet URL Pattern Difference\n\n**In ValueSet JSON** (url field):\n```json\n\"url\": \"http:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.6\"\n```\nUses `http:\u002F\u002F` (no 's')\n\n**In CQL** (valueset declaration):\n```cql\nvalueset \"name\": 'https:\u002F\u002Fexample.org\u002Ffhir\u002FValueSet\u002F2.16.840.1.113762.1.4.1287.6'\n```\nUses `https:\u002F\u002F` (with 's')\n\nThis is intentional and follows GT examples exactly.\n\n### ValueSet File Naming\n\n- File name = Full OID: `2.16.840.1.113762.1.4.1287.6.json`\n- NOT descriptive names like `17022B-indications.json`\n- id field in JSON = file name without .json extension\n",{"name":5,"description":7},"main","b22eca2e974f918ce591c5b2bd829fb7510e0191","Skills\u002Fnhi-cql-generator",18,"https:\u002F\u002Fgithub.com\u002FFDU-INS\u002FInsurance-Skills","https:\u002F\u002Fgithub.com\u002FFDU-INS","Fudan University Department of Risk Management and Insurance","2026-07-12 12:54:34",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add FDU-INS\u002FInsurance-Skills --skill nhi-cql-generator",{"tool":59,"command":60},"bunx","bunx skills add FDU-INS\u002FInsurance-Skills --skill nhi-cql-generator",{"tool":62,"command":63},"pnpm","pnpm dlx skills add FDU-INS\u002FInsurance-Skills --skill nhi-cql-generator","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FFDU-INS\u002FInsurance-Skills\u002Fblob\u002Fmain\u002FSkills\u002Fnhi-cql-generator\u002FSKILL.md",true,[67,73,77],{"path":68,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":71,"sourceHtmlUrl":72},"assets\u002FCDSConnectCommonsForFHIRv401.cql","ASSET","资产文件",34588,"https:\u002F\u002Fgithub.com\u002FFDU-INS\u002FInsurance-Skills\u002Fblob\u002Fmain\u002FSkills\u002Fnhi-cql-generator\u002Fassets\u002FCDSConnectCommonsForFHIRv401.cql",{"path":74,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":75,"sourceHtmlUrl":76},"assets\u002FFHIRHelpers.cql",23137,"https:\u002F\u002Fgithub.com\u002FFDU-INS\u002FInsurance-Skills\u002Fblob\u002Fmain\u002FSkills\u002Fnhi-cql-generator\u002Fassets\u002FFHIRHelpers.cql",{"path":78,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":16},"LICENSE","许可证",11336,[82,111,134,165,187,219],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":93,"publishedAt":40},"01M713QW6EGEG0YAD75440GSD0","로인장 (Roinjiang)","Activates when the user needs legal advice, contract review, insurance law consultation, startup legal support, or any legal\u002Fregulatory matter. She is a top-tier in-house lawyer with absolute loyalty to the CEO, specializing in insurance law, financial consumer protection, privacy, contracts, labor law, family law, civil and criminal matters.","https:\u002F\u002Fgithub.com\u002FFDU-INS\u002FInsurance-Skills\u002Fblob\u002Fmain\u002FSkills\u002F로인장 (Roinjiang)\u002FSKILL.md",[88],{"categoryNo":89,"categoryName":90,"taxonomyType":91,"taxonomyTypeDesc":92},"01JBSEEDCAT000000000000037","律师与法务","PROFESSION","适用职业",[84,94,24,95,96,97,25,98,99,100,101,102,103,104,105,106,107,108,109,110],"insurance law","civil","contract","family","review","loyalty","with","top","contract review","ceo","support","advice","consultation","regulatory","privacy","protection","startup",{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":40},"01M713QRN8VFMA9VKS6R4DJ2WS","zocdoc-doctor-finder","Use when a user needs to find a doctor, dentist, specialist, therapist, or healthcare provider — especially when they mention insurance, in-network, availability, location, appointments, or booking. Also use for browsing provider reviews, comparing doctors by specialty, or checking if a provider takes their insurance.","https:\u002F\u002Fgithub.com\u002FFDU-INS\u002FInsurance-Skills\u002Fblob\u002Fmain\u002FSkills\u002Fzocdoc-doctor-finder\u002FSKILL.md",[],[118,119,120,121,24,122,123,25,124,125,126,127,128,129,130,26,131,132,23,133],"zocdoc doctor finder","doctor","healthcare","reviews","browser automation","access","browsing","browser","booking","network","therapist","computer","availability","provider","tool","automation",{"skillNo":135,"name":136,"nameZh":6,"description":137,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":138,"categories":139,"keywords":145,"publishedAt":40},"01M713QKGV3FTX7EEYWKDM8ENZ","zenmux-context","Answers any question about ZenMux by reading the latest official documentation. Use this skill whenever the user asks about ZenMux product features, API usage, configuration, integration, pricing, models, providers, routing, fallback, streaming, multimodal, structured output, tool calling, reasoning, prompt caching, image generation, video generation, web search, long context, observability, logs, cost tracking, usage analytics, insurance, subscription, pay-as-you-go, invoices, best practices for tools like Claude Code, Cursor, Cline, CodeX, Gemini CLI, opencode, Cherry Studio, Obsidian, Sider, Open-WebUI, Dify, Neovate, GitHub Copilot, OpenClaw, CC-Switch, Immersive Translate, Studio Chat, architecture, benchmarks, FAQ, contact, privacy, terms of service, compliance, or any other ZenMux-related topic. Also trigger when the user writes in Chinese about ZenMux: 文档, 使用指南, 快速开始, API 参考, 最佳实践, 模型路由, 供应商路由, 订阅, 按量计费, 可观测性, 帮助, 常见问题, 接入指南, 配置. Trigger on phrases like \"how to use ZenMux\", \"ZenMux docs\", \"ZenMux API\", \"ZenMux integration\", \"ZenMux 怎么用\", \"ZenMux 接入\", \"ZenMux 配置\". Even if the user doesn't say \"ZenMux\" explicitly but asks about LLM API aggregation, model routing, provider fallback in a context where ZenMux is the project being worked on, this skill should activate.","https:\u002F\u002Fgithub.com\u002FFDU-INS\u002FInsurance-Skills\u002Fblob\u002Fmain\u002FSkills\u002Fzenmux-context\u002FSKILL.md",[140],{"categoryNo":141,"categoryName":142,"taxonomyType":143,"taxonomyTypeDesc":144},"01JBSEEDCAT000000000000016","图像与多媒体","SCENARIO","使用场景",[146,147,148,149,24,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164],"context","zenmux context","Video","chinese","project","web search","translate","search","open","question","pay","image","you","activate","architecture","logs","streaming","cherry studio","how",{"skillNo":166,"name":167,"nameZh":6,"description":168,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":169,"categories":170,"keywords":171,"publishedAt":40},"01M713QHWTBG634BCBV7NBJME1","workers-comp-guide","Guide workers compensation compliance and claims management.\nTRIGGERS - Use when user needs help with workers-comp-guide related tasks.","https:\u002F\u002Fgithub.com\u002FFDU-INS\u002FInsurance-Skills\u002Fblob\u002Fmain\u002FSkills\u002Fworkers-comp-guide\u002FSKILL.md",[],[172,173,174,175,176,24,177,178,23,25,179,100,180,181,182,183,184,185,186],"workers","comp","workers comp","workers comp guide","guide","triggers","workers-comp","tasks","claims management","claims","compliance","help","compensation","management","user",{"skillNo":188,"name":189,"nameZh":6,"description":190,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":191,"categories":192,"keywords":202,"publishedAt":40},"01M713QF45VMV1685AFNF1GPMA","weekly-kpi-report","Generate McKinsey-style board presentation PPTs from weekly auto insurance data. Automatically calculates 16+ KPIs, creates executive-level slides with actionable insights, and supports week-over-week comparisons. Use when user uploads insurance cost data (Excel\u002FCSV) and requests board report, weekly presentation, executive briefing, or mentions keywords like 董事会汇报, 周报PPT, 经营分析演示, McKinsey-style reports.","https:\u002F\u002Fgithub.com\u002FFDU-INS\u002FInsurance-Skills\u002Fblob\u002Fmain\u002FSkills\u002Fweekly-kpi-report\u002FSKILL.md",[193,196,199],{"categoryNo":194,"categoryName":195,"taxonomyType":143,"taxonomyTypeDesc":144},"01JBSEEDCAT000000000000003","演示文稿",{"categoryNo":197,"categoryName":198,"taxonomyType":143,"taxonomyTypeDesc":144},"01JBSEEDCAT000000000000004","电子表格",{"categoryNo":200,"categoryName":201,"taxonomyType":91,"taxonomyTypeDesc":92},"01JBSEEDCAT000000000000034","行政与办公人员",[203,204,205,206,207,24,208,209,210,211,25,212,213,38,214,215,216,217,23,218],"weekly","weekly kpi report","kpi","report","xlsx","actionable","insights","briefing","auto","board report","reports","演示","data","presentation","slides","uploads",{"skillNo":220,"name":221,"nameZh":6,"description":222,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":223,"categories":224,"keywords":228,"publishedAt":40},"01M713QA9WJDHMNVTTY1ENRKVB","wealth-advisory","Wealth management and financial planning for HNW and UHNW clients. Activate when the user\nmentions wealth management, financial planning, retirement, estate planning, tax planning,\nGRAT, IDGT, trust, asset allocation, withdrawal rate, Monte Carlo simulation, goals-based\ninvesting, tax-loss harvesting, Roth conversion, insurance, annuity, mortgage strategy,\nconcentrated stock, family office, direct indexing, 529 plan, charitable giving, donor-advised\nfund, private foundation, or asks about personal finance strategy, inheritance, long-term\nfinancial planning, or UHNW advisory.","https:\u002F\u002Fgithub.com\u002FFDU-INS\u002FInsurance-Skills\u002Fblob\u002Fmain\u002FSkills\u002Fwealth-advisory\u002FSKILL.md",[225],{"categoryNo":226,"categoryName":227,"taxonomyType":91,"taxonomyTypeDesc":92},"01JBSEEDCAT000000000000040","财务",[229,230,24,231,232,25,159,233,234,235,236,237,238,239,240,241,242,243,244,245],"wealth advisory","advisory","stock","inheritance","conversion","indexing","plan","simulation","personal finance","rate","allocation","asset","direct","personal","investing","trust","planning"]