medOS ultra

Revenue Platform Master Plan

Strategic envelope: 8 payment models, VBHC, Contract aggregate, 15 bounded contexts, agentic recommender-first substrate, multi-country tiers.

16 min read diagramsUpdated 2026-05-26docs/architecture/revenue-platform-master-plan/00-MASTER.md

Master reference for the medOS-ultra revenue platform — multi-country, multi-payment-model, multi-care-setting, agent-centric (recommender-first), with the data layer + LLM lift + payment model abstraction that the existing FFS RCM pipeline doesn’t yet have.

Status: Active design — 2026-05-27 (verified against code) Owner: Platform Architecture Scope: End-to-end revenue lifecycle, Thailand / Japan / Philippines / US-activation-ready, with explicit gap audit and agentic substrate


0. How to Use This Master Plan

This directory contains 14 linked documents. Read them in this order:

  1. This file (00-MASTER.md) — executive summary + index + core principles
  2. 10-unified-domain-design.md — the philosophical anchor; three-axes model; 25-aggregate substrate; 11 bounded contexts; country profile as YAML; the architectural test
  3. 11-design-gaps-and-fixes.md — honest audit of 15 design gaps in the original sketch; 5 new bounded contexts to add; revised build order
  4. 12-agentic-substrate.md — agents as first-class peers; opt-in / recommender-first runtime; agent decision provenance; promotion pipeline
  5. Then doc-by-doc 01 → 09 for the implementation details
  6. 13-multi-country-export-registry.md for the export-layer refactor (P0 ships now)

1. Executive Summary

medOS-ultra has a working FFS RCM pipeline (CHECKOUT → CODING → VALIDATION → CLAIM_BATCH → INVOICE → REP_RESULT → AR_SETTLEMENT → SETTLED) used today for Thai NHSO/OFC/SSS, PhilHealth, and Japanese private insurance claims. Type-safe, shared canonical contracts, 80% code reuse across countries.

But three blind spots will block long-term value:

  1. The data layer treats terminology as strings, not relations. terminology_cache and icd10_master are duplicates. Coded diagnoses live as JSONB arrays in encounter_journey_cache.coding_output. CC/MCC lists don’t exist. Every downstream analytics or LLM use case bottoms out on this. See 02.

  2. Payment model is hardcoded as FFS. UCS OPD in Thailand is capitated. Japanese 介護 is unit-based. US Medicare Advantage will be VBHC. Medical tourism is bundled cash. The current architecture mis-attributes revenue across all of these. See 04.

  3. Country profiles are scattered, not orthogonal. Currency, locale, catalog version, submission format, and scheme list are mixed in infrastructure/market-packs/. New country = touch market packs + seeds + transformers + edge functions. The architecture conflates clinical reality (universal), payment model (mostly universal), and regulatory profile (country-specific). See 06.

The master plan does not rewrite what works. It adds four new layers to the existing pipeline, all additive:

  • Substrate layer — terminology backbone + encounter-coded-diagnosis projection + catalog versioning + shared core entities (02, 08)
  • Payment-model handler layer — N handlers for N payment models; country profile registry binding local schemes to handlers; Contract aggregate as central routing (04, 05, 07)
  • LLM/Ollama lift layer — clinical-context NLP for coding suggestions, CDI queries, denial risk, suspect-diagnosis prompts; PHI vs public-corpus separation (03)
  • Agentic substrate layer — agents as first-class peers; identity + authorization + decision provenance + work management; shipped recommender-first until evidence justifies autonomous promotion (12)

After honest review of the design (11) we also add five new bounded contexts: Clinical Decision Support, Authorization, Work Management, Integration, Financial Trace. Total: 15 bounded contexts.

Each layer is additive. The existing FFS RCM pipeline keeps working unchanged.


2. The Core Insight — Three Axes That Get Conflated

Most legacy HIS systems (Epic, Cerner, HOSxP, e-PHIS) fail at multi-country / multi-payment because they collapse three independent axes into one:

Tier Axis Universality
1 Clinical Reality — what actually happened to the patient Universal across countries, payment models, care settings
2 Payment Model — how money flows for that care Mostly universal across countries; bound to schemes per country via the Contract aggregate
3 Regulatory Profile — what data must be reported, in what format, to whom, when Highly country-specific

Keeping them orthogonal makes the system portable. Collapsing them forces a fork for every new market.

The Contract aggregate is what makes the three tiers cohere. Every dollar that moves anywhere traces back to a Contract that knows: payer, provider org, attribution rules, payment model handler, carve-outs, catalog versions, submission emitter. See 07.

Full unified design with the 25-aggregate table, 11 base + 5 added bounded contexts, country-profile YAML syntax, and the architectural test (can three country teams build their profiles in parallel without coordination?) → 10.


3. Document Index

# Document Topic
00 Master plan This file — executive summary, principles, index, code-verification
01 Medical Coder — Current State What exists today; what’s leaking revenue
02 Data Layer Foundation Terminology backbone, projection, catalog versioning
03 LLM / Ollama Revenue Integration Clinical-context NLP, RAG corpus, CDI, PHI separation
04 Payment Model Taxonomy 8 payment models; handler architecture; country bindings
05 VBHC Architecture HCC recapture, attribution, quality measures, care management
06 Multi-Country Domain Three-tier architecture; country profiles for TH/JP/PH/US
07 Contract Aggregate The central abstraction holding the three tiers together
08 Shared Substrate Core entities every payment model and country shares
09 Implementation Roadmap Phased build order; dependencies; effort estimates
10 Unified Domain Design Philosophical anchor. 25-aggregate table, 11 bounded contexts, country-profile YAML, architectural test, Nidāna parallel
11 Design Gaps and Fixes Honest audit. 15 gaps in original sketch + 5 new bounded contexts + revised build order
12 Agentic Substrate Agents as first-class peers, opt-in, recommender-first. Identity + authorization + provenance + promotion pipeline
13 Multi-Country Export Registry Country exporter registry pattern; P0 refactor ships now; JP/PH/US exporters when customers materialize

4. Code-Verification Findings (against actual repo, 2026-05-27)

4.1 What’s verified to exist in code

Claim Verification File path / commit
RevenuePipelineContract.ts exists with 7 stages + metadata + transitions + bridge fns web/src/containers/medical-coder/components/RevenuePipelineContract.ts (commit cf0643fc1)
Frontend CodingStatus has 7 values Same file
Backend CoderStatus enum exists with 7 values ✅ but typo: REGISTED (should be REGISTERED) packages/platform-api-schema/src/administration/coder/entity/CoderStatus.ts
Backend ↔ Frontend 1:1 enum alignment ⚠️ LOOSE, not strict. 3 pairs match exactly (IN_PROGRESS, PENDING_VALIDATION, VALIDATION_FAILED). 4 pairs have different semantic framings (backend = registration lifecycle “Await Register/Registed/Acknowledged”; frontend = completion lifecycle “AWAITING/COMPLETED/REVIEW_REQUESTED/REVIEW_COMPLETED”). See 11 §3
ReceivablesDataGrid has PIPELINE column with stage chips (Coding/Validate/ClaimBatch/Invoice) + color coding web/packages/rcm-kit/src/financial/components/ReceivablesDataGrid.tsx line 686 (commit be2b6e934)
Cross-nav chips on Revenue Collection → Medical Coder / Reports / FP&A ✅ 3 navigate calls verified web/src/containers/revenue-collection/index.tsx lines 262/270/277 (commit be2b6e934)
Shared encounter pool wired to ReceivablesGrid + ClaimAdjustmentDrawer web/packages/rcm-kit/src/financial/mock-data/shared-encounter-pool.ts (commit bf33e922a)
PipelineStageIndicator.tsx web/src/containers/medical-coder/components/PipelineStageIndicator.tsx
Sandbox targets shipped: CoderWorkstationTarget, CodingWorklistTarget, MedicalCoderLandingTarget, ClaimAdjustmentDrawerTarget, ReceivablesGridTarget, MedicalCoderImportsTarget ✅ 6 targets web/sandbox/targets/ (commits 7c349cedd, 7c8e869c7, bf33e922a)
manualExportEClaim wired to ReceivablesDataGrid export button ✅ Thailand-only web/packages/rcm-kit/src/financial/components/manualExportEClaim.ts (commit b16ce222d)
§11 Backend Service Architecture documented in rcm-pipeline-unified-contract.md ✅ at line 722 docs/architecture/rcm-pipeline-unified-contract.md (commit fa502999b)
7 market packs (medos-thailand/japan/philippines/universal/english, bizbox-thailand, _template) infrastructure/market-packs/
llm_audit_log table infrastructure/medbase/migrations/20260514c_llm_platform.sql
8 NestJS financial modules + 4 Deno edge functions for RCM services/financial/src/api/financial/modules/, infrastructure/medbase/functions/

4.2 What’s forward-looking (specified but not yet built)

Item Status Spec doc
country-profiles/ directory with versioned YAML profiles ❌ Not implemented — current market packs are the embryonic version 10 §7, 11 §2 Gap 6
agent_identity + agent_decision provenance tables ❌ Not implemented — current llm_audit_log is embryonic 12 §3
encounter_coded_diagnosis normalized projection ❌ Not implemented — codes still live as JSONB in encounter_journey_cache.coding_output 02 §4
Bitemporal columns (valid_from/to + tx_from/to) on aggregates ❌ Not implemented — only created_at / updated_at today 11 §2 Gap 2
Contract aggregate + encounter_payment_binding ❌ Not implemented — current model has scheme but no per-encounter contract binding 07
capitation_ledger + capitation handler ❌ Not implemented — UCS OPD encounters currently route through FFS pipeline incorrectly 04 §3.2
Country export registry (export-formats/) ❌ Not implemented — manualExportEClaim.ts still single-file Thailand-only 13
cdi_query + claim_edit_history tables ❌ Not implemented 02 §9.4-9.5

4.3 Action items surfaced by verification

  1. Fix backend typo REGISTED → REGISTERED as part of either adapter-layer mapping or data migration (11 §3)
  2. Add explicit enum mapping table at gateway adapter — backend tracks registration lifecycle, frontend tracks completion lifecycle; the 1:1 mapping in prior notes is aspirational
  3. country-profiles/ and agent_identity are next — they unblock the multi-country and agentic phases respectively
  4. encounter_coded_diagnosis projection is the highest-leverage unbuilt substrate — every leakage view, denial pattern, CDI query, and Ollama-grounded suggestion bottoms out on this

4A. What Has Shipped Since This Master Plan Was Written

The following implementation milestones landed during this session (verified against git log and grep):

Pipeline + Worklist

  • cf0643fc1RevenuePipelineContract.ts (7 stages, transitions, prerequisites, bridge fns) + PipelineStageIndicator visual component
  • bf33e922a — All RCM surfaces wired to shared encounter pool (80 deterministic encounters via getSharedMockPool()); ClaimAdjustmentDrawer sandbox target
  • be2b6e934PIPELINE column on ReceivablesDataGrid with color-coded stage chips + cross-nav chips on Revenue Collection (→ Medical Coder, Reports, FP&A)
  • 7c349ceddMedicalCoderLanding sandbox target
  • 7c8e869c7CodingWorklist sandbox target with worklist → CoderWorkstation flow
  • b16ce222d — Export test harness + manualExportEClaim wired to receivables grid

Documentation

  • 93c90b091docs/architecture/rcm-pipeline-unified-contract.md (718 lines, 8-stage lifecycle, canonical types, dual data source mapping)
  • fa502999b§11 Backend Service Architecture added: 8 NestJS financial modules, coder management in administration, 4 Deno edge functions, event-driven NATS transitions, backend↔frontend enum alignment table

What this means for the roadmap

These shipments cover the frontend visualization + contract layer of the original P0 substrate cleanup phase. They do not yet touch:

  • Backend encounter_coded_diagnosis projection
  • Contract aggregate
  • Country export registry refactor
  • Bitemporal columns
  • Agentic substrate

So the visible UI demonstrates the intended architecture (pipeline as first-class, cross-nav between surfaces, shared deterministic data) while the substrate underneath is still single-tenant FFS with JSONB-of-codes. This is the right shipping order — visualize the target architecture in the UI first so stakeholders can see + agree on the direction, then build the substrate that makes it durable.

The natural next P0 work is the multi-country export registry refactor (13 §6) — ~270 LOC that extracts the working Thai exporter into the registry pattern. It’s pure refactor (no behavior change for Thailand), it unblocks Japan/PH/US exporters when those customers materialize, and it can ship without coordinating with any backend work.


5. Implementation Phases — Summary

Full detail in 09-implementation-roadmap.md. Revised order incorporating the gap audit (11 §5):

Phase Stage What Unblocks
P0a Substrate cleanup Resolve terminology_cacheicd10_master duplication; add catalog_version registry Everything below
P0b Identity + Authorization with multi-tenancy from day one auth_subject (HUMAN/AGENT/SYSTEM/PATIENT); tenantId on every aggregate Multi-tenancy + agents
P0c Multi-country export refactor Extract Thai exporter into registry; generic CSV fallback; wire VITE_COUNTRY_CODE JP/PH/US exporters when needed (13)
P1 Data layer foundation ALTER icd10_master, encounter_coded_diagnosis, cc_mcc_list (DRG-version-keyed), bitemporal columns Revenue leakage detection, LLM grounding, audit defense
P2 Agent decision provenance + work management agent_decision table, work_item with bidirectional flows, command dispatch with uniform Subject All future agents
P3 LLM revenue lift (recommender-mode) Ingest ICD-10-TM corpus into llm_embeddings; Coding Suggestion Agent in recommender mode; CDI query workflow 5–15% adjRW recovery via human acceptance
P4 Contract aggregate + payment-model abstraction contract + encounter_payment_binding + revenue_recognition_ledger; FFS handler extracted All payment models below
P5 Capitation handling (TH UCS OPD) capitation_ledger + PMPM accrual + cap utilization Thai OPD revenue visibility
P6 Remittance + appeals + financial trace remittance_file, remittance_line, denial_reason, appeal, financial_trace Closes the dollar trace gap
P7 Bundled / episode-based episode aggregate; episode P&L; risk-share calculation NHSO pilots, medical tourism, BPCI-ready
P8 Japan 介護 (LTC units) Multi-provider care plan, unit budget, recertification cycle Japan market activation
P9 Self-pay / medical tourism Real-time pricing, multi-currency, packages, deposits Bangkok cash-patient revenue
P10 CDS context + integration context Clinical Decision Support reading Tier 1+2; legacy system adapters Point-of-care safety; phased migrations
P11 VBHC activation Attribution roster, HCC engine, quality measure engine, CCLF ingestion US market activation
P12 Agent promotion pipeline Per-tenant evidence collection; RECOMMENDER → ACTOR promotion workflow Selective agent autonomy
P13 Edge models Workers’ comp, motor TPL, research, charity Completeness

6. Cross-Cutting Principles

  1. Additive, not destructive. The existing FFS RCM pipeline keeps working. New layers consume the same encounter event stream and add new processors.

  2. Substrate before features. Data-layer cleanup precedes payment-model expansion precedes LLM lift. Building Ollama integration before terminology backbone produces a system that hallucinates codes that don’t exist in Thai-TM.

  3. One Contract per encounter line, but encounters can route to multiple Contracts. Primary + secondary + carve-out. No floating revenue.

  4. Payment model handlers are country-agnostic. Same DRG handler runs Thai-DRG, MS-DRG, DPC/PDPS, G-DRG. Country profiles supply groupers as plugins.

  5. Regulatory emitters are country-specific. NHSO 43-files, レセプト, X12 837 are concrete output formats. One emitter per (country, payer, format) tuple in the registry (13).

  6. PHI never leaves the hospital. Public reference data (ICD-10, MoPH guidelines) is precomputed and shipped. PHI embeddings (clinical text queries) only on-prem via Ollama.

  7. Catalog versions are first-class. Every coded artifact records the catalog version active at coding time. Reconstructing historical claims must be possible years later.

  8. Encounter event stream is the contract between Tier 1 and Tier 2. Payment-model handlers subscribe to clinical events. Clinical workflows don’t know about payment models. CDS context (11 §2 Gap 1) makes the unavoidable feedback loop explicit.

  9. Bitemporal everywhere. Every aggregate carries valid_from/to + tx_from/to. Projections re-derivable as-of any (validTime, txTime) tuple. Historical encounters use the catalog version active at their time of service, not “today.”

  10. Multi-tenancy from day one. tenantId on every aggregate. Three explicit tiers within services: tenant-isolated, tenant-shared-by-country, globally-shared.

  11. Agents as first-class peers, recommender-first. Every agent ships with runtime_mode='RECOMMENDER'. Substrate (identity, authorization, decision provenance, work management) is built for full agency; runtime gates it behind opt-in. Promotion to ACTOR requires evidence, compliance sign-off, and is per-tenant per-action (12 §5).

  12. Agents propose, humans dispose. No agent action affecting external systems (claim submission, document creation, money movement) executes without human authorization. Internal state changes are agent-authorizable per tier. Some actions stay human-authorized forever (see 12 §5.2).

  13. Kill switch on every agent. One-row update disables. Every dashboard surfaces it.

  14. Country profile is data, not code. Versioned YAML registry with effective dates per scheme + per submission format + per terminology binding. New country = new profile, no code changes (10 §7, 11 §2 Gap 6).

  15. The architectural test. Can a Thai team build the Thailand profile, a Japanese team build the Japan profile, and a Philippine team build the PH profile in parallel without coordination beyond the substrate contract? If yes, the separation is right. If no, country-specific concerns have leaked — refactor before the next country.


7. The Single Most Important Discipline

The hard part is not the design. It’s the discipline of not letting country-specific exceptions, payment-model-specific shortcuts, or agent autonomy without evidence leak upward into the substrate when shipping pressure hits.

Examples of how that discipline breaks:

  • A Thai-only field added to the universal Patient table because PR was due Friday
  • An if (countryCode === 'TH') branch inside the FFS handler
  • A NHSO submission format check inside the coding-rules-engine
  • A 介護-specific column added to Encounter
  • A US-specific HCC field made required on the universal CodedDiagnosis
  • An agent promoted from RECOMMENDER to ACTOR without evidence “because the user trusts it”
  • An agent given write authority that bypasses the work queue “to speed up the demo”

Each one is small. None of them seem to break anything immediately. Cumulatively they kill the architecture. Within 24 months the system can no longer be ported to a new country, can no longer be safely audited, can no longer be promoted to the next agent capability tier.

When shipping pressure forces a fix, the fix MUST be in the correct layer even if slightly slower to write there. There is no “we’ll refactor later.” Later doesn’t happen.


8. The Three Architectural Loops to Name + Observe + Tune

Per 11 §6:

  1. Coding → Revenue → Documentation feedback loop — denied claim → CDI insight back to clinical → AI training signal forward → better next-encounter coding. Cycle time is the KPI.

  2. Patient → Provider → Tenant → Patient loop in BIA/HealthWallet — consent revocation flows downstream; AI training notifications flow upstream. Sovereignty requires explicit loops.

  3. Country profile → Regulatory pipeline → Country profile loop — regulatory PDF ingestion updates the profile → changes future submission formats → changes incoming denials → informs next ingestion. This loop is the moat. Longer it runs, better medOS knows each country’s regulatory landscape — but only if the loop is closed.

Loops are good when intentional + observable; bad when accidental + silent. Every loop must be named, instrumented, and tunable.


This master plan complements the following existing docs in docs/architecture/. It is the strategic envelope that says where they fit in a multi-country, multi-payment-model, agentic future:

This master plan does not replace any of them. It is the integration narrative.


10. Reading Order for New Engineers

  1. Start here (00-MASTER.md)
  2. 10-unified-domain-design.md — the philosophical anchor
  3. 11-design-gaps-and-fixes.md — the honest audit
  4. 12-agentic-substrate.md — agents-as-peers, recommender-first
  5. 06-multi-country-domain.md — three-tier model
  6. 04-payment-model-taxonomy.md — 8 payment models
  7. 07-contract-aggregate.md — central abstraction
  8. 08-shared-substrate.md — core entities
  9. 01-medical-coder-current-state.md — what exists today
  10. 02-data-layer-foundation.md — immediate data work
  11. 03-llm-revenue-integration.md — AI lift (recommender-mode)
  12. 13-multi-country-export-registry.md — P0 refactor that ships now
  13. 05-vbhc-architecture.md — VBHC specifics when US activates
  14. End with 09-implementation-roadmap.md — build order

11. The One-Sentence Summary

medOS-ultra is the only multi-country healthcare platform that treats clinical reality, payment model, and regulatory profile as three orthogonal axes and treats agents as first-class peers shipped recommender-first — making it the architectural equivalent of cloud-native infrastructure against on-prem enterprise software, with the substrate as the moat.

Ask Anything