# CoCM Gaps Implementation Roadmap

Last updated: 2026-08-03

This file tracks the remaining work from `Meduvo_CoCM_Complete_Master_Analysis (2).md`,
especially Part 12: "A Day at Community Health PC".

Use this file as the source of truth when resuming the gradual implementation.

## Accepted Decisions

- The current web kiosk QR flow is acceptable for MVP.
- We are not building physical Tablet #3 inventory/assignment right now.
- We are not building MDM/native tablet lockdown right now.
- Agora will be used for integrated telehealth/warm-handoff video.
- Agora details have been added to `.env`; do not commit real credentials.
- APNs VoIP/CallKit will be used for iOS call wake-up notifications.
- Stedi will be used as the clearinghouse for eligibility and claims.
- Stedi integration should replace CSV-only billing as the main claim workflow.

## Gap Register

Resolved gaps remain listed here for traceability.

1. PHQ-9 Q9 safety logic does not match the MD narrative. **Resolved 2026-08-02.**
   - Current behavior hard-stops on any positive numeric risk answer.
   - Required behavior: "Several days" should not hard-stop if protocol says only higher answers hard-stop.

2. No dedicated front desk/check-in role.
   - Current workaround is `clinic_admin`.
   - Need limited patient search and kiosk QR handoff permissions.

3. Multi-assessment packet flow is fragile.
   - Current kiosk can rely on pending assessment row ordering.
   - Need explicit packet model for PHQ-9 + GAD-7 assignment.

4. Severity labels are missing or not consistently exposed. **Resolved 2026-08-02.**
   - Need labels such as PHQ-9 `16 = Moderately Severe`, GAD-7 `11 = Moderate`.

5. CoCM decision support is incomplete. **Resolved 2026-08-02.**
   - Need explicit "Consider CoCM referral" recommendation based on scores/status.

6. Consent UX needs polishing.
   - Backend consent exists, but in-room patient consent/signature flow needs better UX.

7. BHCM auto-assignment is missing.
   - Current system depends on `bhcm_id` already being set.

8. Agora warm handoff needs completion.
   - Session create/join/token flow exists.
   - Need full patient/provider call flow, end call endpoint, duration capture, and iOS VoIP call wake-up.

9. Care plan create/update API is incomplete.
   - Care goals exist.
   - Provider API is read-only.

10. Repeat assessment reminders are not automated.
    - Need automatic PHQ-9/GAD-7 follow-up tasks.

11. Outreach logs are not structured.
    - Current time log notes are free text.

12. BHCM psychiatric escalation request is missing.
    - Psychiatrist recommendations exist, but BHCM-owned escalation button/task is missing.

13. Billing staff access is blocked.
    - `billing_staff` is setup-only right now.
    - Need limited billing/reporting/claim access.

14. Billing readiness mismatch exists.
    - Part 12 says 68 minutes should be claim-ready/green for 99492.
    - Current engine resolves `99492`, but traffic light can be amber.

15. Release Claim workflow is missing.
    - Current system supports billing computation/reporting/export.
    - Need claim release, lock, status, and audit flow.

16. Payer eligibility verification is not automated.
    - Stedi 270/271 should handle this.

17. Clearinghouse response handling is missing.
    - Need Stedi 277CA and 835 handling.

## Implementation Phases

### Phase 1: Clinical Safety and Scoring

- [x] Add answer-level safety trigger rules.
- [x] Update `SafetyAnswerEvaluator` to use per-question/per-answer thresholds.
- [x] Ensure PHQ-9 Q9 score `1` can record risk context without hard-stopping.
- [x] Add tests for PHQ-9 Q9 scores `0`, `1`, `2`, `3`.
- [x] Add severity-band config/model/helper for PHQ-9.
- [x] Add severity-band config/model/helper for GAD-7.
- [x] Return severity labels/colors in provider patient summary APIs.
- [x] Show severity labels in patient chart.
- [x] Add CoCM decision-support output such as "Consider CoCM referral".

### Phase 2: Stable Assessment Packet Flow

- [x] Create `assessment_packets` table.
- [x] Create `assessment_packet_items` table.
- [x] Store patient, assigned-by user, ordered assessment templates, and status.
- [x] Link kiosk handoff token/session to an assessment packet.
- [x] Update PCP assignment UI to create one packet for selected assessments.
- [x] Update kiosk flow to load packet items in order.
- [x] Stop relying on latest pending assessment response ordering.
- [x] Add tests for PHQ-9 + GAD-7 packet completion.

### Phase 3: Roles and Access Control

- [x] Decide between new `front_desk` role or expanding `clinical_support`.
- [x] Allow front desk/check-in users to search patient by MRN/name/DOB.
- [x] Allow front desk/check-in users to generate kiosk QR handoff.
- [x] Prevent front desk/check-in users from broad clinical chart access.
- [x] Enable `billing_staff` access to billing dashboard.
- [x] Enable `billing_staff` access to time ledger.
- [x] Enable `billing_staff` access to claim readiness.
- [x] Enable `billing_staff` access to Stedi claim status after Stedi claim tracking exists.
- [x] Add permission tests for front desk/check-in role.
- [x] Add permission tests for billing staff role.

### Phase 4: Consent and Referral

- [x] Improve patient-facing consent screen.
- [x] Display versioned CoCM consent text.
- [x] Add/refine signature capture UX.
- [x] Add clear consent refusal path.
- [x] Ensure refusal does not block routine care.
- [x] Create BHCM assignment service.
- [x] Auto-assign BHCM by online status, capacity, and lowest caseload.
- [x] Add tests for auto-assignment.

### Phase 5: Agora Telehealth

- [x] Confirm `.env` has `AGORA_APP_ID`.
- [x] Confirm `.env` has `AGORA_APP_CERTIFICATE`.
- [x] Confirm `.env` has `AGORA_TOKEN_TTL_SECONDS`.
- [x] Add config/health warning if Agora config is missing.
- [x] Complete PCP warm-handoff join flow.
- [x] Complete BHCM warm-handoff join flow.
- [x] Complete patient warm-handoff join flow.
- [x] Render provider-side Agora video for PCP and BHCM with local/remote views and call controls.
- [x] Ensure all participants fetch short-lived Agora tokens.
- [x] Send APNs VoIP PushKit notifications for iOS warm-handoff calls.
- [x] Register provider/patient iOS VoIP tokens with the backend.
- [x] Add provider/patient iOS CallKit PushKit delegates, entitlements, and background modes.
- [x] Route patient CallKit accept action into the telehealth incoming flow.
- [x] Add `POST /warm-handoff-sessions/{id}/end`.
- [x] Add `ended_at`, `ended_by_user_id`, and final duration fields if needed.
- [x] Add `ended` status to warm-handoff lifecycle.
- [x] Generate suggested direct-call time log after call end.
- [x] Let BHCM confirm/edit suggested time log before submission.
- [x] Add tests for token gating, patient access, end call, and suggested time log.
- [x] Add PCP cancel endpoint for pending warm-handoff sessions before BHCM joins.

### Phase 6: BHCM Workflows

- [x] Add provider API endpoint to create care goal.
- [x] Add provider API endpoint to update care goal.
- [x] Add provider API endpoint to mark care goal achieved.
- [x] Add BHCM UI for care plan management.
- [x] Add structured outreach model or extend time logs with outreach fields.
- [x] Track contact method.
- [x] Track reached/not reached.
- [x] Track mood/status summary.
- [x] Track next action and next follow-up date.
- [x] Link outreach to billing time logs where applicable.
- [x] Add scheduler for repeat PHQ-9/GAD-7 tasks.
- [x] Show repeat assessment due tasks on BHCM dashboard.
- [x] Add flow to assign/send repeat assessments.

### Phase 7: Psychiatric Escalation

- [x] Add BHCM "Escalate to Psychiatric Consultant" button/action.
- [x] Create psychiatric review request/task from BHCM side.
- [x] Route request to psychiatrist queue.
- [x] Let psychiatrist respond with recommendation.
- [x] Let PCP/BHCM approve or defer recommendation.
- [x] Decide whether psychiatrist portal is MVP or feature-flagged Phase 2.
  - Decision: current admin psychiatry portal is the MVP psychiatrist surface; no separate portal/feature flag added yet.
- [x] Add tests for escalation request and recommendation review lifecycle.

### Phase 8: Billing Rules and Claim Readiness

- [x] Separate "billing code resolved" from "traffic-light threshold".
- [x] Decide final meaning of green/amber/red.
  - Decision: green = resolved billing code + full readiness checklist complete; amber = code resolved but review gaps remain, or no code yet but approaching next minute band; red = no resolved code and not approaching/not computed.
- [x] Align 68-minute `99492` readiness with dashboard language.
- [x] Add manual billing review checklist:
  - [x] Consent on file.
  - [x] Active CoCM enrollment.
  - [x] Care plan updated.
  - [x] Time logged.
  - [x] Assessment score available.
  - [x] Eligibility verified.
  - [x] Provider NPI present.
  - [x] Payer ID present.
- [x] Add tests for claim readiness and traffic-light behavior.

### Phase 9: Stedi Clearinghouse Integration

- [x] Add `config/stedi.php`.
- [x] Add `.env.example` placeholders:
  - [x] `STEDI_API_KEY`
  - [x] `STEDI_BASE_URL`
  - [x] `STEDI_ENV=test`
  - [x] `STEDI_WEBHOOK_SECRET`
  - [x] `STEDI_TEST_CLAIMS=true`
- [x] Add patient insurance fields:
  - [x] payer name
  - [x] payer ID / trading partner service ID
  - [x] member ID
  - [x] group number
  - [x] subscriber details
- [x] Add provider/practice billing fields:
  - [x] billing provider NPI
  - [x] rendering provider NPI
  - [x] tax ID / EIN
  - [x] service facility address
- [x] Add payer transaction enrollment tracking:
  - [x] `270` eligibility
  - [x] `837P` professional claims
  - [x] `835` ERA
- [x] Add "Check Eligibility" action.
- [x] Send Stedi 270 eligibility request.
- [x] Store Stedi 271 response summary.
- [x] Store active/inactive eligibility status.
- [x] Require eligibility verification before claim release.
- [x] Generate Stedi 837P professional claim JSON from billing period.
- [x] Use test mode/`usageIndicator = T` until production is explicitly enabled.
  - Decision: `STEDI_TEST_CLAIMS=true` keeps JSON claims in test mode; production requires explicit env change.
- [x] Submit claim to Stedi with idempotency key.
- [x] Store Stedi transaction ID and submission response.
- [x] Store submitted payload hash.

### Phase 10: Claim Lifecycle, Webhooks, ERA

- [x] Add claim statuses:
  - [x] `draft`
  - [x] `ready_for_release`
  - [x] `submitted_to_stedi`
  - [x] `accepted_277ca`
  - [x] `rejected_277ca`
  - [x] `paid_835`
  - [x] `denied`
  - [x] `corrected`
  - [x] `voided`
- [x] Add Release Claim button.
- [x] Lock billing period after release/submission.
- [x] Add Stedi webhook receiver.
- [x] Verify Stedi webhook signature.
- [x] Store raw webhook events.
- [x] Retrieve/store 277CA acknowledgments.
- [x] Mark claim accepted or rejected from 277CA.
- [x] Store 277CA rejection reasons.
- [x] Retrieve/store 835 ERA.
- [x] Store payment, adjustment, denial details.
- [x] Link ERA lines to claim/service lines.
- [x] Add correction workflow that creates a new claim version.
- [x] Do not edit submitted claims in place.

### Phase 11: Reporting and Audit

- [x] Add eligibility status to reports.
- [x] Add Stedi claim status to reports.
- [x] Add 277CA status to reports.
- [x] Add ERA/payment status to reports.
- [x] Add unreleased/rejected/paid claim filters.
- [x] Audit eligibility checks.
- [x] Audit claim preview.
- [x] Audit claim release.
- [x] Audit Stedi submission.
- [x] Audit webhook receipt.
- [x] Audit 277CA retrieval.
- [x] Audit 835 retrieval.
- [x] Audit claim correction.
- [x] Audit claim void.

## Recommended Build Order

1. Safety threshold and severity labels.
2. Assessment packet flow.
3. Front desk and billing staff permissions.
4. Consent UX and BHCM assignment.
5. Agora call end and time capture.
6. BHCM care plan, outreach, and repeat reminders.
7. Psychiatric escalation.
8. Billing readiness cleanup.
9. Stedi eligibility.
10. Stedi claim submission.
11. Stedi 277CA/835 webhooks.
12. Reporting, audit, corrections.

## Progress Log

- 2026-08-02: Created this roadmap from the Part 12 simulation and gap review.
- 2026-08-02: Confirmed kiosk QR flow is working and accepted as MVP approach; skipped physical Tablet #3/device inventory and MDM kiosk lock for now.
- 2026-08-02: Confirmed Agora will be used for in-app telehealth/warm handoff.
- 2026-08-02: Confirmed Stedi will be used for clearinghouse eligibility and claims.
- 2026-08-02: Implemented Phase 1 clinical safety/scoring: metadata-driven safety thresholds, PHQ-9 Q9 threshold coverage for scores 0-3, PHQ-9/GAD-7 severity labels, provider-summary decision support, and patient-chart severity display.
- 2026-08-02: Implemented Phase 2 assessment packets: packet/item schema, ordered assignment, kiosk token packet context, packet-aware template/start APIs, kiosk packet completion behavior, and regression tests. Verified packet, safety/provider, and Vite build checks after disk space recovered.
- 2026-08-02: Implemented Phase 3 roles/access: added `front_desk`, allowed limited patient search and kiosk QR handoff without chart access, moved `billing_staff` into approved-tenant billing/report/time-ledger access, added Stedi claim-status tracking visibility, and added focused permission tests.
- 2026-08-02: Added `clearinghouse_claims` foundation for Stedi lifecycle status (`ready_for_release`, `submitted_to_stedi`, `accepted_277ca`, `rejected_277ca`, `paid_835`, `denied`, `corrected`, `voided`) and surfaced latest Stedi status in billing dashboard, billing detail, reports, and claim CSV export.
- 2026-08-02: Implemented Phase 10 claim lifecycle handling: signed Stedi webhook receiver, raw webhook event storage, 277CA accepted/rejected updates with rejection reasons, 835 ERA artifact/payment storage, service-line ERA linking, release button wording, and corrected-claim draft version workflow.
- 2026-08-02: Implemented Phase 11 reporting/audit improvements: eligibility, 277CA, and ERA/payment status on reports and CSV export; unreleased/rejected/paid report filters; named audit payload events for Stedi eligibility, claim preview, release, submission, webhook receipt, 277CA/835 retrieval/processing, and claim correction. Void audit remains pending because the void/cancel workflow is not implemented yet.
- 2026-08-02: Completed provider-side Agora video UI: PCP start now routes into an Agora call room, BHCM incoming handoff reuses the same real video surface, remote/local video tiles render through `AgoraVideoView`, and provider call controls include mic, camera, camera switch, and end/cancel.
- 2026-08-02: Added pending warm-handoff cancellation: backend `POST /warm-handoff-sessions/{id}/cancel`, `cancelled` lifecycle status, PCP-only authorization, no suggested time log for unjoined calls, provider app cancel wiring, and regression tests for cancel/forbidden/joined-call behavior.
- 2026-08-02: Added iOS APNs VoIP/CallKit path for warm-handoff calls: backend APNs VoIP sender using `storage/app/firebase/AuthKey_44ZD2F5TX9.p8`, provider/patient PushKit delegates, VoIP token registration as `apns_voip`, iOS background modes/entitlements, patient CallKit accept routing, and focused APNs backend tests. Real-device delivery still requires confirming the Apple Team ID and provisioning profiles for both bundle IDs.
- 2026-08-03: Added internal Stedi claim void workflow: billing staff/admin can mark eligible draft/submitted/acknowledged/rejected/denied claims as `voided` with a required reason, service lines move to `voided`, the billing period is unlocked locally, and a `stedi_claim_void` audit event records the action. Paid claims remain blocked from this internal void path because they need payer-specific recoupment handling.

## Resume Prompt

When resuming later, say:

`Open COCM_GAPS_IMPLEMENTATION_ROADMAP.md and continue from the next unchecked item.`
