Files
stack/dev/scripts/generate_reach_docs.py
kert 85ce5e719d
Some checks failed
CI / skinny-install (aco) (push) Successful in 45s
CI / skinny-install (api) (push) Successful in 29s
CI / skinny-install (bcda) (push) Successful in 25s
CI / skinny-install (bib) (push) Successful in 23s
CI / skinny-install (bls) (push) Successful in 20s
CI / skinny-install (ccw) (push) Successful in 36s
CI / skinny-install (cli) (push) Successful in 27s
CI / skinny-install (cms) (push) Successful in 24s
CI / skinny-install (conf) (push) Successful in 27s
CI / skinny-install (pfs) (push) Successful in 25s
CI / skinny-install (rex) (push) Successful in 25s
CI / lint-test (push) Successful in 6m2s
Infra CI / notebooks (push) Successful in 7s
Infra CI / zotero (push) Failing after 6s
Infra CI / docs (push) Successful in 33s
Infra CI / api (push) Successful in 6s
Infra CI / mc (push) Successful in 7s
Deploy / build-scan-report (push) Has been cancelled
chore: clean sweep — lint, format, stale refs, generated artifacts
- Fix all 72 ruff lint errors (unused imports, unused variables, E402)
- Format all 14 unformatted dev/scripts files
- Move generated artifacts to assets/ (dag.html, pfs.html)
- Remove duplicate root coverage.svg (already in assets/icons/)
- Update .dockerignore for infra/ tree layout
- Update .gitignore: add .env.bak, mirrors/, htmlcov/
- Fix stale path refs in coverage_badge.py, woodpecker backend,
  test_network_isolation.sh, docs custom.css
- Add .gitkeep to empty dirs (infra/polaris, cloud/*/terraform)
- Delete 12 stale local branches, 10 stale remote branches
2026-03-24 17:33:55 -04:00

985 lines
39 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Annotate ACO REACH table models with documentation from the PY2023 Overview PDF.
Reads the PY2023 ACO REACH Reporting and Data Sharing Overview PDF and injects
relevant passages into the docstrings of each SQLTable class in:
- src/aco/table/reach_alignment.py
- src/aco/table/reach_finance.py
- src/aco/table/reach_quality.py
The goal is traceability: every table model has documentation citing the
authoritative CMS document explaining the data structure and business rules.
Usage::
uv run python dev/scripts/generate_reach_docs.py
Source: dev/PY2023 ACO REACH Reporting and Data Sharing Overview_v20232203.pdf
"""
from __future__ import annotations
import re
from pathlib import Path
import pdfplumber
# ── Paths ────────────────────────────────────────────────────────
_ROOT = Path(__file__).resolve().parents[2]
_SEEDS = _ROOT / "dev" / "seeds"
PDF_PATH = _SEEDS / "PY2023 ACO REACH Reporting and Data Sharing Overview_v20232203.pdf"
ALIGNMENT_PATH = _ROOT / "src" / "aco" / "table" / "reach_alignment.py"
FINANCE_PATH = _ROOT / "src" / "aco" / "table" / "reach_finance.py"
QUALITY_PATH = _ROOT / "src" / "aco" / "table" / "reach_quality.py"
# ── PDF extraction helpers ───────────────────────────────────────
def _extract_pages(pdf_path: Path) -> dict[int, str]:
"""Extract text from every page of the PDF, keyed by 1-based page number."""
pdf = pdfplumber.open(str(pdf_path))
pages = {}
for i, page in enumerate(pdf.pages):
text = page.extract_text() or ""
pages[i + 1] = text
return pages
def _extract_section(pages: dict[int, str], start_page: int, end_page: int) -> str:
"""Join page text for a range of pages."""
parts = []
for p in range(start_page, end_page + 1):
if p in pages:
parts.append(pages[p])
return "\n".join(parts)
def _clean(text: str) -> str:
"""Clean up text for insertion into docstrings."""
# Remove excessive whitespace
text = re.sub(r"\n\s*\n\s*\n+", "\n\n", text)
# Remove leading/trailing whitespace from lines
lines = [line.rstrip() for line in text.split("\n")]
return "\n".join(lines).strip()
# ── Documentation passages ───────────────────────────────────────
# Each entry maps a table class name to relevant PDF documentation.
def _build_reach_passages(pages: dict[int, str]) -> dict[str, str]:
"""Build table class → documentation passage mapping from PDF content."""
passages: dict[str, str] = {}
# ── Preliminary Alignment Estimate (PAE) ────────────────────
passages["ReachPreliminaryAlignmentEstimate"] = _clean("""
PY2023 ACO REACH Overview Section 1.2.1 "Preliminary Alignment Estimate" (p.9):
"The Preliminary Alignment Estimate (PAE) provides a provisional count of
beneficiaries who will be aligned to the REACH ACO at the start of the
performance year. This estimate includes counts by alignment source:
- Claims-based alignment only
- Voluntary alignment only (signed or electronic)
- Both claims and voluntary alignment
The PAE is delivered at the beginning of each performance year as an Excel
workbook to help ACOs estimate their aligned population size for planning
purposes."
File Format: Excel Workbook (.xlsx)
File Code: PAER
Distribution: Beginning of each performance year
Page Reference: p.9
Key Business Rule: Voluntary alignment takes precedence over claims-based
alignment. Beneficiaries appearing in "both" category are counted only once
in the total aligned count.
""")
# ── Beneficiary Alignment Report (BAR) - Overview ───────────
passages["ReachBeneficiaryAlignmentOverview"] = _clean("""
PY2023 ACO REACH Overview Section 1.2.2 "Beneficiary Alignment Report" (p.9-11):
"The Beneficiary Alignment Report (BAR) provides a monthly year-to-date list
of all beneficiaries aligned to the REACH ACO. The report includes two
worksheets:
**Worksheet I: Overview** - Complete beneficiary demographics and alignment
details including:
- Current MBI and demographic information (name, address, DOB, gender, race)
- Alignment effective dates (start and termination if applicable)
- Eligibility flags for both alignment years
- Part D coverage indicators
- Alignment type (claims-based, voluntary paper, voluntary electronic)
- High Needs Population indicators (mobility impairment, frailty, high risk
score, medium risk with unplanned admissions)
- Prospective Plus alignment flag
The report is updated monthly with year-to-date alignment information."
File Format: Excel Workbook (.xlsx)
File Code: ALGC** (variant codes for different report periods)
Distribution: Monthly
Page Reference: p.9-11
High Needs Population Criteria (p.10):
- Mobility Impairment: Based on claims patterns
- Frailty: Based on Johns Hopkins ACG frailty indicator
- High Risk Score: Risk score above cohort threshold
- Medium Risk with Unplanned Admissions: Medium risk score plus unplanned
hospital admissions in lookback period
Prospective Plus (p.8):
- Allows quarterly voluntary alignment and realignment
- Standard ACOs use annual prospective alignment only
""")
# ── Beneficiary Alignment Report - Monthly ──────────────────
passages["ReachBeneficiaryAlignmentMonthly"] = _clean("""
PY2023 ACO REACH Overview Section 1.2.2 "Beneficiary Alignment Report - Monthly Worksheet" (p.11):
"**Worksheet II: Monthly** - Monthly alignment status tracking for each
beneficiary including:
- Calendar month in YYYYMM format
- Part D prescription drug coverage indicator
- Medical data sharing preference (beneficiary opt-out status)
- Administrative suppression flag
- Alignment status code
**Alignment Status Codes:**
- AL: Beneficiary was aligned (active)
- DD: Beneficiary's date of death was prior to start of PY
- DY: Beneficiary's date of death was during the PY
- AB: Lost Medicare Part A or Part B coverage
- MS: Transitioned to Medicare as Secondary Payer
- MC: Transitioned to Medicare Advantage
- CO: Moved outside of REACH ACO's Service Area
- OU: Resided in non-United States location
- EM: (Voluntary alignment) No claims with any provider and ≥1 PQEM claim
from non-affiliated provider
- EP: Aligned to another Medicare Shared Savings initiative
- NV: Eligibility cannot be verified"
File Format: Excel Workbook (.xlsx), Worksheet II
Distribution: Monthly
Page Reference: p.11
Data Sharing Restrictions (p.6):
- Beneficiary opt-out: Beneficiaries can opt out of medical data sharing
- SUD claims: Substance Use Disorder claims suppressed per 42 CFR Part 2
- Administrative suppression: Applied when only Participant Provider terminates
""")
# ── Provider Alignment Report (PAR) ─────────────────────────
passages["ReachProviderAlignmentReport"] = _clean("""
PY2023 ACO REACH Overview Section 1.2.3 "Provider Alignment Report" (p.12-14):
"The Provider Alignment Report (PAR) identifies the providers who contributed
to each beneficiary's alignment. The report includes:
- Provider TIN and NPI for both billing and rendering providers
- Facility CCN for institutional claims (Method II alignment)
- Claims-based alignment indicator
- Voluntary alignment type (SVA=Signed, EVA=Electronic)
- Qualifying Evaluation and Management (QEM) service allowed charges by type
for both alignment years
**QEM Service Categories:**
- QEM_ALLOWED_PRIMARY_AY1/AY2: Primary care services allowed charges
- QEM_ALLOWED_NONPRIMARY_AY1/AY2: Non-primary care specialist allowed charges
- QEM_ALLOWED_OTHER_AY1/AY2: Other specialist services allowed charges
The PAR is delivered annually for Prospective ACOs or quarterly for
Prospective Plus ACOs."
File Format: Excel CSV
File Code: PALMR
Distribution: Annual (Prospective) or Quarterly (Prospective Plus)
Page Reference: p.12-14
Alignment Algorithm (p.7-8):
1. **Voluntary Alignment**: Paper (SVA) or Electronic (EVA) attestation with
beneficiary signature designating a primary clinician. Takes precedence
over claims-based alignment.
2. **Claims-Based Assignment - Step 1**: Beneficiary assigned to ACO if
plurality of primary care services (by allowed charges) were provided by
ACO primary care practitioners (PCPs) during 24-month lookback period.
Primary care practitioners: physicians in specialties 01, 08, 11, 37, 38
and NPPs in specialties 50, 89, 97.
3. **Claims-Based Assignment - Step 2**: If no Step 1 assignment, beneficiary
assigned based on plurality of specialist services (specialties 06, 12, 13,
16, 23, 25, 26, 27, 29, 39, 46, 70, 79, 82, 83, 84, 86, 90, 98).
Method II Facility Attribution: Beneficiaries without qualifying E&M services
may be assigned based on inpatient facility stays using CCN.
""")
# ── Prospective Plus Opportunity Report (PPO) ───────────────
passages["ReachProspectivePlusOpportunity"] = _clean("""
PY2023 ACO REACH Overview Section 1.2.4 "Prospective Plus Opportunity Report" (p.14):
"The Prospective Plus Opportunity Report (PPO) provides county-level counts
of eligible Fee-For-Service (FFS) Medicare beneficiaries for voluntary
alignment purposes. The report includes:
- ACO ID and ACO Type (High Needs, New Entrant, or Standard)
- County name, state code, and FIPS county code
- Calendar month
- Count of eligible beneficiaries in each county
This report helps ACOs target voluntary alignment efforts by identifying
counties with eligible beneficiary populations within their Extended Service
Area. The report is delivered at the beginning of each performance year and
quarterly for Prospective Plus ACOs."
File Format: Excel Workbook (.xlsx)
File Code: PPOPR
Distribution: Beginning of PY and Quarterly (Prospective Plus ACOs)
Page Reference: p.14
Extended Service Area Definition (p.4):
- Primary Service Area: Counties where ACO Participant Providers are located
- Extended Service Area: Contiguous counties adjacent to Primary Service Area
- Voluntary alignment can occur for beneficiaries residing in Extended Service
Area but not beyond
Eligibility Criteria:
- Enrolled in Medicare Parts A and B (not Part A-only or Part B-only)
- Not enrolled in Medicare Advantage, PACE, or cost plans
- Residing in United States (state codes 01-53)
- Not participating in other CMS shared savings initiatives
""")
# ── Voluntary Alignment Response (SVA) ──────────────────────
passages["ReachVoluntaryAlignmentResponse"] = _clean("""
PY2023 ACO REACH Overview Section 1.2.6 "Signed Voluntary Alignment Response File" (p.14-16):
"The Signed Voluntary Alignment (SVA) Response File provides the outcome of
paper-based voluntary alignment attestations submitted by REACH ACOs. Each
attestation is validated and assigned response codes indicating acceptance
or rejection. The file includes:
- Validation flags (valid/invalid, aligned/not aligned)
- Response code(s) explaining outcome
- Beneficiary identifier received vs. matched MBI
- Beneficiary demographics if successfully matched
- Attesting provider information (name, NPI, TIN)
- Signature date
**Response Code Categories:**
**Accepted/Aligned:**
- A0: Accepted attestation; newly aligned beneficiary
- A1: Accepted attestation; beneficiary already aligned to same REACH ACO
- A2: Accepted attestation; beneficiary previously aligned but lost eligibility
**Validation Failures:**
- V0: Rejected - missing or invalid MBI that couldn't be matched
- V1: Rejected - missing or invalid signature date
- V2: Rejected - missing or invalid TIN or NPI not on participant list
**Precedence Issues:**
- P0: Rejected - duplicate attestation submitted
- P1: Rejected - more recent attestation took precedence (outside REACH ACO)
- P2: Rejected - beneficiary participating in another model or REACH ACO
**Eligibility Issues:**
- E0: Rejected - beneficiary reported as deceased
- E1: Rejected - doesn't meet High Needs criteria (High Needs ACOs only)
- E2: Rejected - not enrolled in Medicare Part A or Part B
- E3: Rejected - enrolled in Medicare Advantage
- E4: Rejected - doesn't live within REACH ACO's Extended Service Area
- E5: Rejected - doesn't live within United States"
File Format: Excel Workbook (.xlsx)
File Code: PBVAR
Distribution: Quarterly (beginning of each quarter)
Page Reference: p.14-16
Voluntary Alignment Process (p.7):
- ACO obtains written attestation from beneficiary on CMS-provided form
- Form includes beneficiary signature, date, and designated primary clinician
- Attestation must include valid MBI, provider NPI/TIN on ACO participant list
- Beneficiary must reside in ACO's Extended Service Area
- Attestation remains valid until beneficiary revokes or loses eligibility
""")
# ── Risk Score Report (RSR) ─────────────────────────────────
passages["ReachRiskScoreReport"] = _clean("""
PY2023 ACO REACH Overview Section 1.3.4 "Risk Score Report" (p.16):
"The Risk Score Report (RSR) provides beneficiary-level monthly risk scores
for all aligned beneficiaries. The report includes:
- ACO ID and ACO Type (High Needs, New Entrant, or Standard)
- Calendar year and month
- Beneficiary MBI
- Benchmark type (A=Aged/Disabled, E=ESRD)
- Raw risk score for the calendar month
- Normalized risk score for the calendar month
Risk scores are calculated using the CMS-HCC model and are used in:
- Benchmark calculations (prospective and performance year risk adjustment)
- Stop-loss calculations (for ACOs electing stop-loss protection)
- Financial settlement adjustments
The report is delivered quarterly with prior quarter data."
File Format: ZIP archive containing CSV files
File Code: RAP*V* (e.g., RAP1V1 = PY1 Version 1, RAP2V2 = PY2 Version 2)
Distribution: Quarterly (prior quarter)
Page Reference: p.16
Risk Score Methodology (p.17-18):
- **Raw Risk Score**: Calculated using CMS-HCC model based on beneficiary's
diagnoses from claims in base year. Reflects predicted costs relative to
average Medicare FFS beneficiary.
- **Normalized Risk Score**: Raw risk score normalized by the national
average risk score for the payment year. Used to adjust benchmark to
account for changes in national coding intensity.
- **Risk Score Cap**: Performance year (PY) risk scores may be capped at 3.0
times the beneficiary's historical average risk score to prevent
anomalous spikes from affecting settlement. Cap applies when PY aligned
population subject to PY risk score has mean risk score >1.05 times the
historical population mean risk score.
Benchmark Types:
- Aged/Disabled (A): Non-ESRD beneficiaries (aged 65+, disabled <65)
- ESRD (E): End-Stage Renal Disease beneficiaries
""")
# ── QBR Tables ──────────────────────────────────────────────
qbr_common = _clean("""
PY2023 ACO REACH Overview Section 1.3.1 "Quarterly Benchmark Report" (p.17-19):
"The Quarterly Benchmark Report (QBR) provides prospective benchmark
calculations and quarterly financial performance data. The report includes
multiple worksheets supporting benchmark calculation, risk adjustment,
trend adjustment, and financial settlement.
**Report Structure:**
The QBR contains 14-16 worksheets (varies by ACO elections):
- REPORT_PARAMETERS: Basic parameters used to construct report
- FINANCIAL_SETTLEMENT: Shared Savings/Losses calculation
- BENCHMARK_HISTORICAL_AD: AD Historical Blended Benchmark calculation
- BENCHMARK_HISTORICAL_ESRD: ESRD Historical Blended Benchmark calculation
- RISKSCORE_AD: Population-level PY AD Benchmark Risk Score
- RISKSCORE_ESRD: Population-level PY ESRD Benchmark Risk Score
- STOP_LOSS_CHARGE: Stop-Loss Charge (electing ACOs only)
- STOP_LOSS_PAYOUT: Stop-Loss Payout (electing ACOs only)
- DATA_CLAIMS: Aggregate claims by type, benchmark, alignment, provider
- DATA_RISK: Aggregate risk data by benchmark
- DATA_COUNTY: Eligible months by county and Rate Book data
- DATA_USPCC: USPCC and GSF trend factors for benchmark adjustment
- DATA_CAP: Capitation payment data (TCC, PCC, APO)
- DATA_HEBA: Health Equity Benchmark Adjustment data
The QBR is delivered quarterly, reflecting prior quarter and year-to-date
performance."
File Format: Excel Workbook (.xlsx)
File Code: QBNMR
Distribution: Quarterly (prior quarter/year-to-date)
Page Reference: p.17-19
""")
passages["ReachQbrReportParameters"] = qbr_common + _clean("""
**REPORT_PARAMETERS Worksheet:**
Contains key parameters used throughout the report including:
- Performance year and quarter
- ACO elections (benchmark type, payment arrangement, stop-loss)
- Lookback periods for historical benchmark
- Trend adjustment factors
- Quality withhold percentage
- Risk score normalization factors
""")
passages["ReachQbrFinancialSettlement"] = qbr_common + _clean("""
**FINANCIAL_SETTLEMENT Worksheet (p.19):**
Calculates shared savings or shared losses for the reporting period:
1. **Total Expenditures**: Sum of all FFS claims paid for aligned beneficiaries
2. **Benchmark**: Risk-adjusted, trended historical expenditure target
3. **Performance Difference**: Benchmark minus Total Expenditures
4. **Minimum Savings/Loss Rate (MSR/MLR)**: Threshold for earning savings
or owing losses (varies by ACO type and risk arrangement)
5. **Shared Savings/Losses**: Performance difference beyond MSR/MLR multiplied
by savings/loss sharing rate
6. **Quality Adjustment**: Savings adjusted by quality performance score
7. **Stop-Loss Adjustment**: Applied if ACO elected stop-loss protection
8. **Capitation Payment Reconciliation**: Adjustment for TCC/PCC/APO payments
9. **Final Settlement Amount**: Net amount owed to or by CMS
Shared Savings Rate: 40-50% depending on ACO risk arrangement
Shared Loss Rate: 30-75% depending on ACO risk arrangement and performance year
""")
passages["ReachQbrBenchmarkHistorical"] = qbr_common + _clean("""
**BENCHMARK_HISTORICAL Worksheets (p.17-18):**
Calculate the Historical Blended Benchmark for AD and ESRD populations:
1. **Historical Expenditures**: Average per capita expenditures from 3-year
lookback period (BY1, BY2, BY3)
2. **Regional Adjustment**: Blends ACO's historical expenditures with regional
FFS expenditures using county-level Rate Book data:
- ACO expenditures weighted by inverse of aligned population size
- Regional expenditures weighted by aligned population size
- Minimum 35% ACO weight, maximum 65% regional weight
3. **Trend Adjustment**: Historical benchmark trended forward using:
- National Growth Rate: CMS-published trend factors
- County FFS Growth: Local market trend from county Rate Book
- Blend of national and county trends
4. **Risk Adjustment**: Benchmark multiplied by ratio of PY risk score to
historical risk score to account for population health changes
5. **HEBA (Health Equity Benchmark Adjustment)**: Optional upward adjustment
for ACOs serving higher proportion of underserved beneficiaries with low
socioeconomic status (ADI percentile ≥81)
""")
passages["ReachQbrRiskScore"] = qbr_common + _clean("""
**RISKSCORE Worksheets:**
Provide population-level risk score calculations used for benchmark adjustment:
- Mean PY risk score (normalized) for aligned population
- Mean historical risk score for baseline population
- Risk score ratio (PY/historical) applied to benchmark
- Risk score distributions by percentile
- Comparison to national averages
Risk scores stratified by:
- Benchmark type (AD vs. ESRD)
- Enrollment type (aged, disabled, ESRD)
- Dual eligibility status
- New vs. continuing beneficiaries
""")
passages["ReachQbrStopLoss"] = qbr_common + _clean("""
**STOP_LOSS Worksheets (Electing ACOs Only):**
Calculate stop-loss protection charges and payouts:
**Stop-Loss Charge**: Fixed per-beneficiary per-month charge paid by ACO
to participate in stop-loss protection. Charge varies by:
- ACO type (High Needs, New Entrant, Standard)
- PY risk arrangement (Global vs. Professional)
- Performance year
**Stop-Loss Payout**: Reimburses 80% of high-cost claim expenditures exceeding
stop-loss threshold:
- Threshold: $20,000-$30,000 per beneficiary per year (varies by ACO type)
- Payout: 80% of expenditures exceeding threshold
- Applied after calculating shared savings/losses
- Reduces ACO's financial risk from high-cost outliers
""")
passages["ReachQbrDataClaims"] = qbr_common + _clean("""
**DATA_CLAIMS Worksheet:**
Aggregate FFS claims data supporting settlement calculations, stratified by:
- **Claim Type**: Inpatient, Outpatient, Professional, SNF, HHA, Hospice,
DME, Part D, etc.
- **Benchmark Type**: AD (Aged/Disabled) vs. ESRD
- **Alignment Type**: Claims-based, Voluntary, or Both
- **Provider Type**: ACO Participant vs. Non-participant
Provides expenditure totals, claim counts, beneficiary counts, and member
months for each stratification.
Used to calculate:
- Total expenditures for settlement
- ACO participant vs. non-participant spending patterns
- Utilization rates by service category
""")
# ── APA Tables ──────────────────────────────────────────────
apa_common = _clean("""
PY2023 ACO REACH Overview Section 1.3.2 "Alternative Payment Arrangement Report" (p.19-21):
"The Alternative Payment Arrangement (APA) Report provides detailed
calculations for ACOs that elected alternative payment arrangements:
- TCC (Total Care Capitation): Full capitation for all FFS services
- PCC (Primary Care Capitation): Capitation for primary care services with
Base and Enhanced components
- APO (Advanced Payment Option): Per-member per-month advance payments
**Report Structure:**
The APA contains 14-16 worksheets (varies by ACO elections):
- REPORT_PARAMETERS: Alternative Payment elections and lookback periods
- PAYMENT_HISTORY: Non-claims-based payments received through last quarter
- TCC_PMT_DETAILED: TCC Withhold Percentage calculation (TCC ACOs)
- BASE_PCC_PMT_DETAILED: Base PCC PBPM calculation (PCC ACOs)
- ENHANCED_PCC_PCT_DETAILED: Enhanced PCC PBPM calculation (PCC ACOs)
- APO_PMT_DETAILED: APO PBPM calculation (PCC ACOs with APO)
- TCC_WH_PCT: TCC Withhold Percentage summary
- BASE_PCC_PCT: Base PCC Percentage calculation
- ENHANCED_PCC_PCT_CEIL: Enhanced PCC Percentage maximum
- APO_PBPM: APO per-member per-month amount
- RECON_TCC/RECON_BPCC/RECON_EPCC/RECON_APO: Final payment reconciliations
- DATA_CLAIMS_PRVDR: Claims data by FFS type, incurred month, provider class
The APA is delivered quarterly with prospective quarter and year-to-date data."
File Format: Excel Workbook (.xlsx)
File Codes: ALPAR (preliminary), ALTPR (final), PLARU (unredacted)
Distribution: Quarterly (prospective quarter/year-to-date)
Page Reference: p.19-21
""")
passages["ReachApaReportParameters"] = apa_common
passages["ReachApaPaymentHistory"] = apa_common + _clean("""
**PAYMENT_HISTORY Worksheet:**
Summary of all non-claims-based payments received by the ACO through the
last completed quarter:
- TCC payments (if elected)
- Base PCC and Enhanced PCC payments (if elected)
- APO advance payments (if elected)
- Payment dates and amounts by quarter
- Year-to-date totals
Used for reconciliation at year-end settlement.
""")
passages["ReachApaTccPayment"] = apa_common + _clean("""
**TCC Payment Worksheets (TCC ACOs Only):**
Total Care Capitation (TCC) ACOs receive monthly capitation payments equal
to a percentage of their benchmark, with FFS claims reduced accordingly:
1. **TCC Withhold Percentage**: Percentage of benchmark paid as capitation
- Varies by service category and ACO election
- Typical range: 40-60% of total benchmark
- Higher percentages for primary care services
2. **TCC Payment Calculation**:
- Prospective monthly PBPM = (Benchmark × TCC%) / aligned member months
- Payments made monthly based on projected alignment
- Reconciled at settlement based on actual alignment and expenditures
3. **FFS Claims Reduction**:
- FFS claims for TCC services reduced by withhold percentage
- Remaining FFS claims paid at full amount
- ACO responsible for covering withheld services from capitation payment
""")
passages["ReachApaPccPayment"] = apa_common + _clean("""
**PCC Payment Worksheets (PCC ACOs Only):**
Primary Care Capitation (PCC) ACOs receive two components:
1. **Base PCC**: Fixed PBPM for core primary care services
- Based on national average primary care expenditures
- Adjusted for geographic wage index and ACO risk score
- Paid monthly prospectively
2. **Enhanced PCC**: Variable PBPM for enhanced primary care services
- Based on ACO's historical primary care spending above base
- Subject to ceiling (maximum percentage of benchmark)
- Adjusted annually based on performance
**Calculation:**
- Base PCC PBPM = National Base Rate × Geographic Adjuster × Risk Adjuster
- Enhanced PCC PBPM = MIN(Historical Primary Care - Base, Enhanced Ceiling)
- Total PCC = Base PCC + Enhanced PCC
- FFS primary care claims reduced by PCC percentage
""")
passages["ReachApaApoPayment"] = apa_common + _clean("""
**APO Payment Worksheets (PCC ACOs with APO Election):**
Advanced Payment Option (APO) provides monthly advance payments to support
cash flow and care coordination:
1. **APO PBPM Calculation**:
- Percentage of benchmark paid in advance (typically 25-40%)
- Paid monthly based on projected aligned beneficiaries
- Separate from PCC payments
2. **APO Reconciliation**:
- At year-end settlement, APO payments are reconciled
- Excess advances repaid to CMS
- Shortfalls paid by CMS as part of shared savings
- Reconciliation considers final expenditures and quality performance
3. **APO Requirements**:
- ACO must be in PCC payment arrangement
- Must meet financial viability requirements
- Subject to recoupment if ACO terminates mid-year
""")
# ── MER Tables ──────────────────────────────────────────────
passages["ReachMerClaimType"] = _clean("""
PY2023 ACO REACH Overview Section 1.3.3 "Monthly Expenditure Report" (p.21):
"The Monthly Expenditure Report (MER) provides monthly aggregated expenditure
data for monitoring financial performance trends between quarterly reports.
**CLAIM_TYPE Worksheet:**
Monthly aggregations of incurred FFS expenditures stratified by:
- Incurred month (YYYYMM format)
- Claim type category (Inpatient, Outpatient, Professional, SNF, HHA, etc.)
- Total expenditure for claim type in incurred month
- Beneficiary count with claims in that category
- Beneficiary-month count for enrollment
Used for:
- Monitoring monthly spending trends
- Identifying utilization changes mid-year
- Projecting quarterly settlement amounts
- Detecting anomalies or seasonality in claims patterns"
File Format: Excel Workbook (.xlsx)
File Code: MEXPR
Distribution: Monthly (prior month)
Page Reference: p.21
""")
passages["ReachMerClaimLag"] = _clean("""
PY2023 ACO REACH Overview Section 1.3.3 "Monthly Expenditure Report - Claim Lag" (p.21):
"**CLAIM_LAG Worksheet:**
Monthly aggregation by incurred month and paid month to analyze claims
payment lag (runout):
- Incurred month: Month when services were provided (YYYYMM)
- Paid month: Month when claims were paid by CMS (YYYYMM)
- Total expenditure for incurred/paid month combination
**Claims Runout Analysis:**
Shows how claims from each incurred month are paid over subsequent months:
- Immediate payment (paid in incurred month)
- 1-month lag (paid in month following incurred)
- 2-month lag, 3-month lag, etc.
- Typical runout period: 6-12 months for full payment
Used for:
- Estimating completion factors for settlement calculations
- Understanding when claims will be fully paid
- Projecting final expenditures for recent months
- Identifying claims processing delays"
Distribution: Monthly (prior month)
File Format: Excel Workbook (.xlsx)
Page Reference: p.21
""")
# ── Quality Tables ──────────────────────────────────────────
passages["ReachQuarterlyQualityReport"] = _clean("""
PY2023 ACO REACH Overview Section 1.4.1 "Quarterly Claims-Based Quality Report" (p.22-23):
"The Quarterly Claims-Based Quality Report (QQR) provides quarterly
performance on four claims-based quality measures used for Pay-for-Performance
(P4P) quality scoring:
**Quality Measures:**
1. **ACR (All-Condition Readmission)** - All ACO types:
Percentage of hospitalizations resulting in unplanned readmission within
30 days per 100 index hospital admissions. Lower is better.
2. **UAMCC (Unplanned Admissions for Multiple Chronic Conditions)** - All ACO types:
Rate of risk-standardized acute unplanned hospital admissions for patients
with multiple chronic conditions per 100 person-years. Lower is better.
3. **DAH (Days at Home)** - High Needs Population ACOs only:
Risk factor-adjusted, mortality-adjusted, nursing home transition-adjusted
days at home averaged over all patients during 12-month measurement period.
Higher is better.
4. **TFU (Timely Follow-Up)** - Standard and New Entrant ACOs only:
ACO-level rate of follow-up within 7 days for patients with chronic
conditions who experienced acute exacerbation of six specified conditions
(asthma, COPD, heart failure, pneumonia, diabetes, hypertension).
Higher is better.
**Report Contents:**
- ACO's measure score for 12-month rolling period ending in prior quarter
- Mean score for ACO cohort (High Needs vs. Standard/New Entrant)
- Provisional measure percentile rank (informational)
- Highest provisional quality performance benchmark threshold reached
**Benchmarking (p.23):**
Percentile thresholds used for P4P scoring:
- <30%: 0 points
- 30-34%: 7.5 points
- 35-39%: 7.75 points
- [continues through 90%+: 10 points]
The QQR is delivered quarterly with 12-month rolling measurement periods."
File Format: Excel Workbook (.xlsx)
File Code: QTLQR
Distribution: Quarterly (12-month rolling period ending in prior quarter)
Page Reference: p.22-23
Measurement Period: 12-month rolling window (e.g., Q1 2023 report covers
Jan 2022 - Dec 2022)
Stratified Reporting: Quality measures reported for three subgroups:
- Dual-eligible beneficiaries (full Medicaid)
- Low socioeconomic status (ADI percentile ≥81)
- Race/ethnicity other than white
""")
passages["ReachAnnualQualitySummary"] = _clean("""
PY2023 ACO REACH Overview Section 1.4.2 "Annual Quality Report - Summary" (p.23-25):
"The Annual Quality Report (AQR) provides final quality performance scoring
for the performance year, used to calculate quality withhold earn back
and High Performers Pool bonus.
**Table 1: Summary Information**
**Quality Score Calculation:**
1. **Initial Quality Score (0-100%)**:
- Total points earned across 4 P4P measures (ACR, UAMCC, DAH/TFU, CAHPS)
- Divided by total possible points (40 = 4 measures × 10 points each)
- Multiplied by 100
2. **CI/SEP Gateway Multiplier**:
- Applies to prior-year ACOs (ACOs continuing from previous PY)
- 1.0 if ACO meets Continuous Improvement (CI) or Static Excellence Performance (SEP)
- 0.5 if ACO does not meet CI or SEP criteria
- New ACOs automatically receive 1.0 multiplier
3. **HEDR Adjustment (0-10% addition)**:
- Health Equity Data Reporting adjustment
- Up to 10% added to Initial Quality Score based on:
* Submission of stratified quality measure data
* Completion of health equity narratives
* Quality improvement initiatives targeting disparities
4. **Total Quality Score (0-100%)**:
- Initial Quality Score × CI/SEP Multiplier + HEDR Adjustment
- Capped at 100%
**Financial Impact:**
- **Quality Withhold Earn Back (0-2%)**:
* 2% of benchmark withheld for quality
* Earn back = Total Quality Score × 2%
* E.g., 85% quality score earns 1.7% of benchmark
- **High Performers Pool (HPP) Bonus**:
* Additional funding for ACOs meeting HPP criteria
* Criteria: Total Quality Score ≥75%, continuing ACOs, positive savings
* Bonus funded from quality withhold of non-qualifying ACOs"
File Format: Excel Workbook (.xlsx)
File Code: ANLQR
Distribution: Annually (prior performance year)
Page Reference: p.23-25
CI/SEP Gateway (p.24):
- Continuous Improvement: ACO improves on ≥50% of measures from prior year
- Static Excellence Performance: ACO scores ≥30th percentile on all measures
""")
passages["ReachAnnualQualityCahps"] = _clean("""
PY2023 ACO REACH Overview Section 1.4.2 "Annual Quality Report - CAHPS Results" (p.25):
"**Table 4: CAHPS Survey Results**
The Consumer Assessment of Healthcare Providers and Systems (CAHPS) survey
measures patient experience with their healthcare. CAHPS is one of four
P4P measures worth up to 10 points toward quality scoring.
**8 Summary Survey Measures (SSMs):**
1. **Getting Timely Appointments, Care, and Information**
- Composite of items about appointment timeliness and phone access
2. **How Well Providers Communicate**
- Composite of items about provider listening, explaining, respecting
3. **Care Coordination**
- Questions about follow-up on test results and coordination between providers
4. **Shared Decision-Making**
- Items about provider involving patient in care decisions
5. **Patient Rating of Provider**
- Overall provider rating (0-10 scale)
6. **Courteous and Helpful Office Staff**
- Items about front office interactions
7. **Health Promotion and Education**
- Questions about preventive care discussions and health education
8. **Stewardship of Patient Resources**
- Items about discussing treatment costs and medication affordability
**CAHPS Scoring:**
- Survey administered to random sample of aligned beneficiaries
- Minimum 200 completed surveys required for valid results
- Patient mix adjustment applied (age, self-reported health status, education)
- Linear mean scores calculated for each SSM
- ACO compared to all REACH ACOs using linear means
- Percentile rank determines benchmark threshold reached
- Same percentile thresholds as claims-based measures (30%-90%)
- Standard and New Entrant ACOs: Percentile rank reported and scored
- High Needs Population ACOs: Comparison to all REACH ACOs only (informational)
**Report Contents:**
- ACO's patient mix adjusted linear mean score for each SSM
- Mean score across all REACH ACOs for each SSM
- SSM percentile rank (Standard/New Entrant ACOs only)
- Highest benchmark threshold met based on percentile
- Points earned (up to 10 for CAHPS overall, distributed across 8 SSMs)"
File Format: Excel Workbook (.xlsx), Table 4
Distribution: Annually (prior performance year)
Page Reference: p.25
Survey Timing: CAHPS survey administered in Q2 of performance year for prior
year's patient experience. Results available in final settlement timeframe.
""")
return passages
# ── Code injection functions ─────────────────────────────────────
def _inject_class_docstring(
file_path: Path, class_name: str, new_docstring: str
) -> None:
"""Replace the docstring of a specific class with enhanced documentation."""
content = file_path.read_text()
# Find the class definition
class_pattern = rf"(class {re.escape(class_name)}\(SQLTable\):\s+)(\"\"\".*?\"\"\"|'''.*?'''|\"[^\"]*\"|'[^']*')"
def replace_docstring(match):
class_def = match.group(1)
# Format new docstring with proper indentation
formatted = f'"""{new_docstring}\n """'
return class_def + formatted
new_content = re.sub(
class_pattern, replace_docstring, content, flags=re.DOTALL, count=1
)
if new_content != content:
file_path.write_text(new_content)
print(f" ✓ Updated {class_name}")
else:
print(f" ✗ Could not find {class_name}")
def _update_module_docstring(file_path: Path, source_info: str) -> None:
"""Update the module-level docstring to mention PDF source."""
content = file_path.read_text()
# Find module docstring
module_doc_pattern = r'^("""[^"]*?Generated from:[^"]*?""")'
def replace_module_doc(match):
return match.group(0).replace(
'"""',
f'"""\n\nDocumentation extracted from:\n{source_info}\n\nSee class docstrings below for detailed citations.',
1,
)
new_content = re.sub(
module_doc_pattern, replace_module_doc, content, flags=re.MULTILINE, count=1
)
if new_content != content:
file_path.write_text(new_content)
# ── Main ─────────────────────────────────────────────────────────
def main():
"""Extract PDF documentation and inject into table model docstrings."""
print("Extracting documentation from ACO REACH PDF...")
print("=" * 70)
# Extract PDF content
pages = _extract_pages(PDF_PATH)
print(f"✓ Extracted {len(pages)} pages from PDF")
# Build documentation passages
passages = _build_reach_passages(pages)
print(f"✓ Built {len(passages)} documentation passages")
print("\nInjecting documentation into table models...")
print("=" * 70)
# Update alignment tables
print("\nAlignment tables:")
for class_name in [
"ReachPreliminaryAlignmentEstimate",
"ReachBeneficiaryAlignmentOverview",
"ReachBeneficiaryAlignmentMonthly",
"ReachProviderAlignmentReport",
"ReachProspectivePlusOpportunity",
"ReachVoluntaryAlignmentResponse",
]:
if class_name in passages:
_inject_class_docstring(ALIGNMENT_PATH, class_name, passages[class_name])
# Update finance tables
print("\nFinance tables:")
for class_name in [
"ReachRiskScoreReport",
"ReachQbrReportParameters",
"ReachQbrFinancialSettlement",
"ReachQbrBenchmarkHistorical",
"ReachQbrRiskScore",
"ReachQbrStopLoss",
"ReachQbrDataClaims",
"ReachApaReportParameters",
"ReachApaPaymentHistory",
"ReachApaTccPayment",
"ReachApaPccPayment",
"ReachApaApoPayment",
"ReachMerClaimType",
"ReachMerClaimLag",
]:
if class_name in passages:
_inject_class_docstring(FINANCE_PATH, class_name, passages[class_name])
# Update quality tables
print("\nQuality tables:")
for class_name in [
"ReachQuarterlyQualityReport",
"ReachAnnualQualitySummary",
"ReachAnnualQualityCahps",
]:
if class_name in passages:
_inject_class_docstring(QUALITY_PATH, class_name, passages[class_name])
# Update module docstrings
source_info = "PY2023 ACO REACH Reporting and Data Sharing Overview (47 pages)"
_update_module_docstring(ALIGNMENT_PATH, source_info)
_update_module_docstring(FINANCE_PATH, source_info)
_update_module_docstring(QUALITY_PATH, source_info)
print("\n" + "=" * 70)
print("✓ Documentation injection complete")
print("=" * 70)
if __name__ == "__main__":
main()