Mira Mace Deep Dive: Every Box in the Architecture, Dissected
Part 1 (the overview) gave the target architecture. This page opens each box: how parties (vendors, offices, payers, patients) are identified and profiled, how agents update those profiles, how knowledge and learned behaviour are stored across Postgres, a vector index and a graph, how they're retrieved into an agent's context, how schedules and follow-ups are generated, how workflows stay durable across days and crashes, and the internals of the primitives, LLM gateway, channels, human plane, observability and configuration. Part 3 (mock scenarios) turns it into practice interviews. Each section starts with a diagram; the tables, schemas and prose underneath are the detail. Section 11 covers the voice AI platform end to end.
TL;DR: the principles under every box
- Agents never write the truth directly. They emit observations with evidence; a deterministic merge service decides what becomes a fact.
- Behaviour is measured, not narrated. "Answers before 10am 20% of the time" is a statistic computed from interaction events, not an LLM's summary.
- Use the right store per kind of memory: facts and statistics in Postgres; similar past situations and documents in a vector index (pgvector first); relationships in tables first, a graph database only when multi-hop queries earn it.
- Context is assembled, not searched. Each step declares what it needs; a context builder fetches it by key first, then expands, then recalls semantically, within a token budget, with provenance on every item.
- Every wait is a row in the database, not a sleeping process. Timers, leases and an outbox make a workflow survive crashes, deploys and two-week waits.
- Voice is one runtime for every surface: each use case hands it a call spec; code owns the call's agenda, the LLM owns the phrasing, guards check every utterance, and every call ends as an interaction record (section 11).
- Schedules come from three inputs: what the workflow needs, when the party is likely to respond (learned), and what capacity is available.
The expanded map
Text version
INTAKE ─────────────────────────────────────────────────────────────────────────────
companion msg · advocate ask · enterprise referral · inbound call/fax/SMS
└▶ normalise → safety triage → identify patient + party → correlate to open case?
├─ yes → append event to that case
└─ no → classify → workflow match → open case (pinned versions) | none → planner (L1)
RUNTIME ────────────────────────────────────────────────────────────────────────────
event log ─▶ reducer ─▶ state ─▶ scheduler.decide() ─▶ autonomy gate ─▶ outbox
▲ │ │
│ approval task ▼
└──────────── result events ◀── executors (per channel) ◀── dispatcher (capacity, batching)
timers table ─▶ timer poller ─▶ wakes cases leases: one writer per case
PRIMITIVES ─────────────────────────────────────────────────────────────────────────
converse · qualify · obtain · commitment · consent · book · notify · human task · escalate
each: next(state, params, now) → Act | DueAt | Done | Failed (pure)
CONTEXT BUILDER ────────────────────────────────────────────────────────────────────
step spec → key lookups (facts) → graph expansion → semantic recall (filtered) → budget → packet
KNOWLEDGE PLANE ────────────────────────────────────────────────────────────────────
party registry (identity + resolution) observations (append-only, evidence)
facts (current view, freshness) behaviour stats (streaming aggregates)
procedures (IVR paths, who to ask) lessons (candidate → validated → active)
episodic index (pgvector) relationship graph (tables → graph DB later)
patient profile + consents definitions + tenant config (versioned)
LLM GATEWAY ── prompt registry · routing · BAA-aware providers · schemas · guards · budgets · traces
CHANNELS ───── voice runtime · fax in/out · SMS · email · portals → one Interaction shape
HUMAN PLANE ── tasks (approval | exception | human step) · routing · SLAs · packets · labels
EVAL / OBS ─── traces per step and turn · recordings · replay · simulations · metrics · gates1. Parties: identity, profile and how agents keep it current
A party is anyone the system deals with: a DME supplier, a doctor's office, a payer, a pharmacy, a home-health agency, the patient, a caregiver. Mira's vetted vendor database is the seed of this; the design turns it into a shared, continuously updated profile used by every workflow.
1.1 Identity and resolution
The hardest part of a party registry is knowing that "Lakeshore HME", "Lakeshore Home Medical Equipment" and the fax number on a received order are the same party.
- Identifiers: NPI (providers and suppliers have one), tax ID, phone and fax numbers (normalised to E.164), addresses (standardised), emails, portal URLs, Medicare supplier number where known. Stored in
party_identifiers, each with a source and a verified flag. - Seeding: the CMS supplier dataset and the NPI registry give a clean starting set of names, addresses and identifiers. data.cms.gov
- Matching new mentions (a name in a transcript, a fax header, a number that called us):
- Exact match on a strong identifier (NPI, verified phone or fax) → same party.
- Otherwise block by cheap keys (ZIP + first token of name, phone area code), score candidates (name similarity, address match, shared phone), and accept only above a high threshold.
- Ambiguous → a human task "is this the same party?" with the candidates side by side. Never auto-merge on name alone.
- Merges and splits are events (
PartiesMerged,PartySplit), so they can be undone and every fact keeps pointing at the right party. - Locations and people: a supplier can have several locations with different stock and service areas; an office has people ("Maria at the front desk handles orders"). Locations are child parties; people are contacts with roles. Staff names are business contacts, but treat them with care and keep them tenant-scoped if a tenant supplied them.
1.2 What a party profile contains
| Layer | Examples | Where it comes from | Stored as |
|---|---|---|---|
| Identity & contact | Names, NPI, numbers, addresses, hours, timezone, holidays | Datasets, calls, documents, humans | Rows in parties, party_identifiers, party_locations |
| Capability facts | Stocks K0001; accepts assignment; serves ZIP 60614; takes plan X; accepts new Medicare patients; typical delivery 2–3 days | Extracted from calls and documents | Typed facts with evidence, source and freshness |
| Behaviour statistics | Answer rate by hour and weekday; median hold time; callback rate; promise-kept rate; document turnaround; which channel gets results | Computed from interaction events (no LLM) | Aggregates in party_behavior_stats, recomputed incrementally |
| Procedures | IVR path ("press 2, then 4 for orders"); "ask for the DME desk"; "they need the order before quoting a date"; best fax number for orders | Call traces that succeeded; lessons promoted by humans | party_procedures with success counts |
| Relationships | Parent organisation; locations; which payers it's in network with; which providers refer to it | Datasets, documents, case history | Edge tables (graph later) |
| Tenant overlay | "Contracted supplier for tenant A"; preferred; do-not-use; internal notes | Tenant config, advocates | party_tenant_overlay, never visible to other tenants |
parties(id, kind supplier|provider_office|payer|pharmacy|patient|caregiver,
name, parent_id, timezone, status active|merged|closed, created_at)
party_identifiers(party_id, type npi|phone|fax|email|address|portal, value_normalised,
source, verified BOOLEAN, first_seen, last_seen, UNIQUE (type, value_normalised))
party_contacts(id, party_id, role, name, direct_line, tenant_id NULL, last_confirmed)
observations(id, party_id, field, value, evidence_quote, interaction_id, source_type
call|fax_doc|dataset|human|web, observed_at, extractor_version,
validation ok|ungrounded|contradicted) -- append-only, raw
facts(party_id, field, value, confidence_class verified|single_source|contested,
supporting_obs INT[], observed_at, expires_at, PRIMARY KEY (party_id, field)) -- projection
party_behavior_stats(party_id, metric, bucket, value, n, updated_at) -- e.g. answer_rate, 'tue-09'
party_procedures(id, party_id, kind ivr_path|ask_for|precondition|channel_pref,
content JSONB, successes, failures, status candidate|active|retired)
party_tenant_overlay(party_id, tenant_id, preferred, contracted, do_not_use, notes)
1.3 How agents update a profile: the observation → fact pipeline
Text version
call with Lakeshore ends
└▶ extractor (LLM) → observations: {accepts_assignment: yes, quote: "yes, we bill Medicare directly"}
└▶ validator (code + small model)
schema ok? quote in THEIR turns? quote entails the value? (NLI check)
├─ fail → observation stored as ungrounded (kept for audit, never used)
└─ pass ▼
└▶ merge policy (deterministic, per field)
source rank: document > human-verified > call > dataset > web
newer same-rank observation replaces older
disagreement with a recent, higher-or-equal-rank fact → fact = contested
└▶ schedule re-verification (a task or a piggy-back question on the next call)
└▶ facts projection updated; FactChanged event → caches invalidated, open cases notified
in parallel: interaction events → behaviour stats (answered at Tue 09:14, hold 3m, 4 turns)- Why agents don't write facts: an LLM's extraction is a claim. Keeping claims (observations) separate from beliefs (facts) gives an audit trail, lets you re-run the merge when the policy changes, and stops one bad call from overwriting a vetted fact.
- Freshness per field type: stock levels expire in days, service area in months, accepts-assignment in months, NPI never. An expired fact is still shown, but marked stale, and a high-risk gate requires a fresh one before acting.
- Piggy-back verification: when a call to a party is already happening, the converse primitive appends one or two re-verification questions for that party's stale facts. Freshness for free.
- Human vetting: changes to high-impact fields (accepts assignment flipped, party closed) go to a review queue before they're trusted across tenants. That matches how Mira's team already vets the vendor DB.
- Cases react to fact changes: if a supplier a case has chosen becomes "contested" on a gate, that case gets an event and re-checks before booking.
1.4 How agents read a profile: the party brief
The agent never queries tables. A step asks the context builder for a party brief shaped for its purpose:
get_party_brief(party_id, purpose="qualify_supplier", case_id, budget_tokens=600) →
{
"party": "Lakeshore Home Medical Equipment (Chicago, Lincoln Park)",
"call_plan": { "number": "+13125550142", "ivr": "press 2 for orders", "ask_for": "DME desk",
"best_window": "Tue–Thu 10:00–12:00 (answer rate 0.72, n=25)" },
"known": [ { "field": "serves_zip_60614", "value": "yes", "as_of": "2026-10-30", "source": "call" } ],
"stale_or_unknown": [ "stocks_K0001 (stale, 41 days)", "accepts_assignment (unknown)" ],
"watch_out": [ "promised callbacks kept 2/6 times; verify within 1 business day" ],
"recent": [ "2026-11-02: said backordered on K0003 (case 811)" ] // summaries, no other patients' PHI
}
- Assembled deterministically from facts, stats, procedures and recent interaction summaries; the LLM only receives it.
- Purpose-shaped: a qualification call gets the gates it still needs; a booking call gets the confirmed facts and the order reference.
- Provenance on every item (as-of date, source), so the agent can say "last time you told us…" and the trace shows what it knew.
- PHI scoping: recent history about a party never includes other patients' identifiers.
2. Knowledge and memory: what's learned, where it lives, how it's retrieved
2.1 Six kinds of memory, and the right store for each
| Kind | Example | Store | Retrieved by |
|---|---|---|---|
| Facts (semantic, structured) | "Lakeshore serves 60614"; "Mrs. Martinez is on Original Medicare Part B" | Postgres (observations → facts) | Key lookup: party + field, patient + field |
| Behaviour statistics | Answer rate by hour; promise-kept rate; fax turnaround | Postgres aggregates | Key lookup; used as features by scheduling and ranking |
| Procedures | IVR paths; "ask for the DME desk"; "they need the order before quoting" | Postgres rows with success counts | Key lookup by party + purpose |
| Relationships | Patient → care team; supplier → payers in network; office → parent system; provider → suppliers they usually send orders to | Edge tables in Postgres; a graph DB when traversal needs grow | Neighbourhood expansion from the case's entities |
| Episodes (episodic) | Interaction summaries; transcript chunks; resolved cases ("how did we solve a similar coding mismatch?") | Vector index (pgvector) with metadata | Semantic search with hard filters (tenant, patient, party) |
| Documents and guidance | SOPs, payer policies, coverage rules, Medicare publications, tenant playbooks | Vector index + keyword index; source of truth in object storage | Hybrid search (keywords + vectors) and rerank |
Plus two things that look like memory but are config, not learned: workflow definitions and tenant rules. They're versioned and released, never "learned" at runtime.
2.2 Vector index or graph database: when each earns its place
Vector index (start with pgvector)
- For: "find something similar" over unstructured text: past cases, transcripts, SOPs, payer policy documents.
- Why pgvector first: their stack is Postgres; one database means tenant filters, row-level security and deletes work the same way as everywhere else.
- Move to a dedicated vector store when the index outgrows Postgres comfortably or needs features (filtered approximate search at scale) Postgres handles poorly.
- Never the source of truth for a fact; a vector hit is a hint with a pointer back to the record.
Graph (tables first, graph DB later)
- For: multi-hop questions: "suppliers that serve this ZIP, are in network for this patient's plan, and have delivered to patients of this provider within 5 days".
- Start with edge tables and recursive queries; most questions are one or two hops.
- Move to a graph DB (e.g. Neo4j) when traversals get deep or frequent, or when you want graph algorithms (similarity between parties, community detection of referral networks).
- Keep Postgres as the system of record and project into the graph via events, so the graph can be rebuilt.
2.3 How behaviours are learned
Three sources, in order of trust:
- Statistics from events (most trusted). Every interaction emits structured events: dialled at, answered or not, hold time, turns, outcome, promise made, promise kept. Streaming aggregation turns these into behaviour stats per party and time bucket. No LLM involved; the numbers are what happened.
- Procedures from successful traces. When a call reaches the right person after "press 2, then 4", that path is recorded as a candidate procedure; after N successes it becomes active; failures demote it.
- Lessons from reflection (least trusted until validated). A periodic job gives an LLM a batch of interactions for a party or a workflow and asks for patterns, each tied to supporting interaction IDs. Example: "Sunrise Family Medicine processes order requests sent by fax within a day; phone requests usually get a promise that isn't kept (6 of 8 cases)".
- The claim is checked by counting against the event data before it's accepted.
- Lifecycle:
candidate → validated → active → retired(retired when new evidence contradicts it). - Active lessons are hints in context or features in ranking and scheduling, never hard rules. A lesson becomes a rule only when a human promotes it into a workflow definition or tenant config.
lessons(id, scope party|workflow|tenant|global, scope_id, statement, kind channel_pref|timing|precondition|tactic,
evidence_interactions INT[], support_n, counter_n, status candidate|validated|active|retired,
proposed_by reflection|human, validated_at, retired_reason)
2.4 Patient memory
- Profile: plan and coverage, language, timezone, contact preferences, accessibility needs, caregiver and what they're authorised to hear, consents.
- Care team graph: the companion's list of doctors becomes edges patient → provider (role: cardiologist, PCP), each pointing to a provider-office party with its own profile.
- Conversation memory: companion conversations are summarised into dated episodes ("11 Nov: asked about knee pain worsening; advocate informed"). Clinical content is kept verbatim with its source, not paraphrased.
- Strict scoping: patient memory is retrievable only within that patient's cases and only by roles allowed to see it; it never feeds cross-patient lessons except as de-identified statistics.
2.5 The context builder: how memory reaches an agent
Each step's spec declares what it needs. The context builder assembles a context packet in five passes:
Text version
step spec: converse(party=Sunrise, goal=obtain written order, patient=Martinez)
1. key lookups party brief (facts, stats, procedures) · patient fields allowed by disclosure scope
· case state (what's been asked, promises outstanding)
2. graph expansion Martinez → Dr. Chen → Sunrise (ordering provider) · Sunrise → preferred fax line
3. semantic recall top-k episodes: past order requests to Sunrise (any patient, de-identified)
filters: tenant_id, party_id, type=interaction_summary, last 180 days
hybrid search → rerank → dedupe
4. budget fixed slots: brief 600 tokens · case 400 · episodes 400 · guidance 300
5. provenance every item tagged (source, as-of, id) → logged with the trace- Key lookups first, semantic search last: what the step must know shouldn't depend on an embedding's mood.
- Disclosure scope is applied here, before the model sees anything: the qualification call's packet has no patient identifiers at all.
- The packet is logged with the step's trace, so "the agent said X because it was told Y" is always answerable, and the same packet can be replayed against a new prompt.
- Agents can also pull via tools (e.g.
lookup_party_fact) during a call, through the same builder and the same scope rules.
2.6 Risks in a learning memory, and the controls
| Risk | Control |
|---|---|
| Memory poisoning: one confused receptionist's wrong answer spreads to every case | Observations vs facts; source ranking; contested state; re-verification; human vetting for high-impact fields |
| Stale lessons | Lessons carry evidence counts and dates; re-validated periodically; retired on contradiction |
| PHI leaking across patients or tenants | Hard metadata filters at query time; row-level security; episodes about parties stored de-identified; tenant overlays never shared |
| Right to delete / retention | Every memory item points to its source record; deleting a patient deletes or de-identifies derived episodes and embeddings |
| Embedding model changes | Embeddings versioned; re-index in the background; queries pinned to one version until the cut-over |
| Retrieval quality drifts silently | A retrieval eval set: questions with known relevant items; recall@k tracked per release |
3. Schedules: how the system decides when to do things
3.1 Four kinds of scheduled work
| Kind | Example | Created by |
|---|---|---|
| Workflow timers | Retry a supplier in 2 business hours; verify the clinic's promise at 10:00 tomorrow; hold expires | The scheduler's Wait / DueAt results |
| Follow-ups the workflow sets for itself | "Call Sunrise back Thursday 9am if the order hasn't arrived"; "re-confirm delivery the day before" | An explicit ScheduleFollowUp(at, reason, cancel_if) action |
| Recurring schedules | CPAP supplies every 90 days; monthly check-in call; annual plan review | A schedule entity that spawns a case each cycle |
| Human-facing deadlines | Approval SLA; task ageing; escalation if untouched for a day | The human plane |
3.2 Choosing the time: needs × availability × likelihood × capacity
def next_attempt_time(case, party, purpose, now):
earliest = max(now, policy_min_gap(case, party)) # e.g. not twice within 2 business hours
window = party.calendar.open_windows(earliest, horizon=5 business days) # hours, holidays, timezone
window = window ∩ tenant_rules.calling_window(party.kind) # e.g. 8am–8pm recipient local
if purpose.involves_patient:
window = window ∩ patient.contact_window() # preferences, consent
# learned: answer probability by weekday/hour bucket, shrunk toward the party-type average when n is small
score = lambda slot: party.stats.answer_rate(slot, prior=type_average) - delay_penalty(slot - now)
slot = argmax(score, candidate_slots(window, step=15 min))
return slot + jitter(0, 7 min) # avoid stampedes at :00
- Calendars: party hours (learned "closed Fridays after 1pm" or supplied), public holidays per state, timezones with DST handled by the timezone database, never by fixed offsets. The take-home hardcoded Chicago; the platform reads the recipient's timezone.
- Shrinkage for small samples: three answered calls don't prove a pattern, so a party's statistics are blended with its type's average until enough evidence exists.
- Deadlines win: if a step has a hard deadline (an expedited prior-auth, a hold expiring), the scheduler picks the earliest feasible slot instead of the most likely one.
3.3 The dispatcher: capacity, priority and batching
Text version
timer due → action becomes "ready" in the outbox
dispatcher loop:
for each ready action, highest priority first (deadline, patient risk, age):
check capacity: channel concurrency · per-party rate limit · per-tenant quota · model budget
coalesce: other ready actions for the same party within the next 30 min?
→ one call covering several cases (only where disclosure rules allow)
lease → hand to the channel executor- Per-party rate limits: calling the same office five times in an hour for five patients is how you get blocked. Coalescing turns that into one call ("I'm calling about three order requests"), which also matches how advocates work.
- Priorities: urgent and deadline-bound first; background work (vendor enrichment of a new list) fills spare capacity and is shed first under load.
- Back-pressure: if the voice runtime is saturated, actions stay in the outbox and their timers slide; nothing is lost.
3.4 Self-scheduled follow-ups, and cancelling them
# the workflow, after the clinic promises the order by tomorrow:
ScheduleFollowUp(at=business_day(+1) @ 10:00 clinic-local,
reason="verify promised written order",
cancel_if=["OrderReceived"], # an event that makes it moot
on_fire=CallClinic(purpose="verify_promise"))
# persistence
timers(id, case_id, due_at, reason, action JSONB, cancel_on TEXT[], status pending|fired|cancelled)
-- when OrderReceived is appended to the case: UPDATE timers SET status='cancelled'
-- WHERE case_id=$1 AND status='pending' AND 'OrderReceived' = ANY(cancel_on)
- This is Temporal's "updatable timer" pattern built on a table: a durable timer that an incoming event can cancel or move. Temporal docs
- Even if cancellation is missed (a race), the fired action goes through
decide()first, which sees the order already received and does nothing. Belt and braces.
3.5 Recurring schedules
schedules(id, tenant_id, patient_id, workflow_id, rule RRULE|interval, next_run_at, timezone,
active, last_case_id)
-- a poller spawns a case at next_run_at, then computes the next one;
-- idempotency key = schedule_id + period, so a double fire never opens two cases
4. Durability: how a workflow survives days of waiting, crashes and deploys
4.1 The guarantees to state
- No lost decisions: a decision and the actions it produces are committed together, or not at all.
- No duplicate effects: a call, fax or message is performed at most once per decided action, even if the executor retries.
- No lost wake-ups: every wait has a timer row; a case with nothing pending and nothing scheduled is detected and escalated.
- No stuck locks: case leases expire; another worker picks up.
- Waiting costs nothing: a case waiting two weeks for a fax is a row in a table, not a sleeping process or an open connection.
- History is the truth: any case can be rebuilt from its events; any decision can be replayed and explained.
4.2 The mechanics, in one picture
Text version
┌───────── ONE TRANSACTION ─────────┐
event arrives → │ lock case (lease) │
or timer fires │ load snapshot + new events │
│ decide() → actions │
│ append ActionDecided events │
│ insert outbox rows (idempotency key)│
│ upsert timers / cancel timers │
└────────────────────────────────────┘
executor: claim outbox row (SKIP LOCKED) → check interactions table for this key (already done?)
→ perform effect with the key → append result event → mark row done
on failure: attempts+1, next_attempt_at = backoff; after N → append ActionFailed (typed)4.3 Crash matrix
| Crash point | What happens |
|---|---|
| Worker dies before committing a decision | Nothing was written; the lease expires; another worker re-decides from the same events and reaches the same decision (decide is pure). |
| Worker dies after commit, before the executor runs | The outbox row is pending; an executor picks it up. |
| Executor dies mid-call | The telephony provider's status callback (or a timeout sweep) produces CallEnded(outcome=dropped); the workflow's normal retry rules apply. The call's partial transcript is still saved if streamed. |
| Executor performed the effect but died before recording it | On retry, the executor first checks for an interaction with this idempotency key (or asks the provider by its reference) and records the existing result instead of acting twice. Where a provider has no lookup, prefer effects that are naturally idempotent or accept a rare duplicate with an apology path; say so honestly. |
| Deploy during a two-week wait | Nothing is in memory; the new code reads the same rows. The case stays pinned to its workflow version. |
| Timer poller down for an hour | Timers are due rows, not in-memory schedules; when it returns it processes everything overdue, in priority order, respecting calling windows (a missed 4pm call doesn't fire at 9pm; it reschedules). |
| A poison event keeps crashing the reducer | After N failures the case is quarantined, an engineering alert fires, and an advocate is told the case needs attention; other cases keep running. |
| The database fails over | Point-in-time recovery and a replica; at worst, recent decisions are re-made from events, and idempotency keys stop duplicates. |
4.4 Waiting on humans and the outside world
- Human approvals are tasks; their resolution is an event (
ApprovalGranted) that wakes the case. Temporal would call this a signal. - External callbacks (fax delivered, call ended, SMS reply) arrive by webhook → verified → written as events against the case via correlation IDs we generated.
- Every external wait has a deadline and a typed outcome when it expires: no callback is ever waited on forever.
4.5 Versions and long histories
- Pinning: a case runs on the workflow version it started with. Migrations are explicit: dry-run replay on the new version, compare decisions, move the cases that agree.
- Event upcasting: old event shapes are converted when read, never rewritten.
- Snapshots every N events keep load time flat; very long-lived cases (recurring care) can close and open a successor case carrying a summary, the equivalent of Temporal's "continue-as-new".
4.6 Build it, or use Temporal
Everything above is what Temporal provides out of the box: deterministic workflow code replayed from history, activities for side effects with retries, durable timers, signals and updates, and versioning by patching. Temporal docs The trade-off from Part 1 stands: a small Postgres runtime fits their stack and team today; the decide/perform split maps cleanly onto Temporal if timer and retry logic starts to dominate. Either way, the guarantees in 4.1 are what to state in the interview.
5. Primitives: what's inside each one
5.1 The interface
class Primitive(Protocol):
name: str
def init(self, params: dict, case: CaseView) -> TrackState: ...
def next(self, state: TrackState, params: dict, now: datetime) -> Act | DueAt | Done | Failed: ...
def apply(self, state: TrackState, event: Event) -> TrackState: ... # its slice of the reducer
def risk(self, action: Action) -> RiskClass: ... # feeds the autonomy gate
Pure, typed and unit-tested like the take-home's policy. Domain specifics arrive as params from the workflow definition.
5.2 Converse
Text version
PLAN ─▶ PRECHECK ─▶ DIAL/SEND ─▶ IN_CONVERSATION ─▶ EXTRACT ─▶ VALIDATE ─▶ DONE
│ │ │ │
identity/consent no answer, transfer to human, ungrounded → re-ask
scope ok? voicemail → safety stop next time
DueAt(retry)- Plan: the questions still open for this party and goal, the disclosure scope, the party brief, piggy-back re-verification questions.
- Precheck: calling window, consent for the channel, verified number, rate limit.
- In conversation: the voice runtime (or SMS/email thread) runs a call spec; guards check every outgoing utterance.
- Extract and validate: observations with evidence; entailment check; results feed the observation pipeline.
- Outcome is typed: answered-complete, answered-partial, no-answer, voicemail, wrong-number, refused, needs-human.
5.3 Obtain (a document or answer from a party)
- A channel ladder from the definition: e.g. phone ×3 → fax → human task.
- An expectation registered with intake, so the inbound document can be matched (party, patient, document type).
- A validator for the document: for a written order, the six required elements and the expected item code.
- Commitments created when the party promises a date; broken promises move the ladder on.
5.4 Commitment
Text version
MADE(by, what, due_by, evidence) ─▶ WAITING ─▶ KEPT (verified by an event or a check)
└─▶ due_by + grace passes ─▶ BROKEN ─▶ counts against party.promise_kept_rate5.5 Consent
Text version
NOT_ASKED ─▶ EXPLAINED(terms) ─▶ UNDERSTOOD? ─┬─▶ AGREED (evidence: quote) ─▶ recorded in consents
├─▶ DECLINED
└─▶ AGREED_WITHOUT_UNDERSTANDING ─▶ re-explain or humanThe take-home's "agreement without understanding is not consent" becomes a state in the primitive, so every workflow that asks for consent inherits it.
6. The LLM gateway
| Function | Detail |
|---|---|
| Prompt registry | Prompts are versioned artifacts with an owner and an eval suite; a step references prompt_id@version. |
| Routing | Per task type: fast model for live conversation, stronger model for extraction or planning; fallback chain across providers. |
| PHI-aware providers | Requests containing PHI only go to providers under a BAA with the right retention settings; a fallback provider without one gets a de-identified request or none. |
| Structured output | Every non-conversational call has a schema; invalid output is a failed attempt, retried with the validation error as feedback. |
| Guards | Outgoing speech: no identifiers not in the packet, no dollar figures unless supplied, no medical advice; normalise text before matching so spelled-out numbers are caught. |
| Error taxonomy | Timeouts, rate limits and 5xx are infrastructure errors: retried and never counted as a business outcome (the take-home bug). Refusals and invalid output are model errors. |
| Budgets | Tokens and cost per case, per tenant, per workflow; exceeding a budget escalates rather than silently continuing. |
| Tracing | Each call logs prompt version, model, packet ID, latency, tokens, outcome; PHI redacted in logs, full payloads in an access-controlled store. |
7. Channels
7.1 One interaction shape for every channel
interactions(id, case_id, party_id, channel, direction, idempotency_key UNIQUE, provider_ref,
started_at, ended_at, outcome, transcript_uri, recording_uri, document_uri,
disclosures_made JSONB, consent_basis, cost)
Primitives see interactions, not channels. That's what lets the obtain ladder switch from phone to fax without the workflow knowing how either works.
7.2 Voice call lifecycle (outbound)
Text version
dispatcher → voice executor: call spec {party, number, goal, questions, scope, persona, max_min}
→ place call via telephony provider (status callbacks to us)
→ IVR phase: detect menu → choose option (learned path first) → send DTMF
→ hold phase: cheap listener (VAD + music/speech classifier); LLM idle; timeout policy
→ human phase: real-time pipeline (STT → turn detection → LLM → TTS), guards per utterance,
disclosures (AI, recording) at the start
→ voicemail? workflow policy: leave a callback message (no PHI) or hang up
→ end → transcript + recording stored → CallEnded event → extraction7.3 Fax
- Outbound: render the document, send via a fax API with our reference, wait for the delivery receipt (an event), retry on busy.
- Inbound: webhook → store → OCR → classify document type → extract identifiers → correlate to an open expectation (Part 1) → validate the document → event on the case, or a human matching task.
7.4 SMS, email, portals
- SMS and email for patients and some parties, with consent records and opt-out handling; threads are correlated by our reference.
- Payer and provider portals: often the fastest source of a prior-auth status or eligibility. A browser-automation executor behind the same interaction shape, with credentials in a vault and a human fallback; fragile, so treat it as a channel with its own reliability metrics.
8. The human plane in detail
tasks(id, tenant_id, case_id, kind approval|exception|human_step, reason, blocks_track,
queue, priority, assignee, status open|claimed|done|expired, sla_due_at,
packet JSONB, proposed_action JSONB, resolution approved|edited|rejected|done,
resolution_diff JSONB, resolved_by, resolved_at)
- Routing: by tenant, skill (prior-auth specialist), patient assignment (their advocate first), then the general queue.
- Packet: two-line summary, the proposed action, the evidence with sources, the transcripts, what happens if they approve or reject.
- SLA ladder: due soon → reminder; overdue → reassign; long overdue → supervisor. The case keeps running its other tracks meanwhile.
- Labels: the resolution and its diff are training and eval data for that step; approval rate per step drives autonomy promotion.
- Workmate: reads the same queue, ordered by priority, and can resolve items by voice.
9. Observability and replay
trace (per case step): case_id, seq, workflow@v, step, primitive, decision + why,
context_packet_id, prompt@v, model, tokens, latency,
autonomy level applied, gate result, action id, outcome
trace (per voice turn): call_id, turn, audio offsets, STT text + confidence, end-of-turn latency,
LLM first token, TTS first audio, interruptions, guard hits
- Case replay: rebuild state at any sequence number; re-run decide() on a new definition and diff decisions.
- Step replay: re-run a logged context packet through a new prompt or model and diff the output (offline regression on real data).
- Call replay: recorded audio through a new STT or turn-detection setting; compare transcripts and extracted facts.
- Dashboards: per workflow and tenant: autonomy rate, escalations by reason, time to resolution, approval rates, cost; per channel: answer rates, call outcomes, latency percentiles.
10. Configuration resolution
Text version
effective value = platform default
◀ overridden by workflow definition (@ pinned version)
◀ overridden by tenant config (@ pinned version)
◀ overridden by patient preference (only for fields patients may set)
every override is schema-validated; forbidden overrides (e.g. a tenant disabling recording disclosure) are rejected at save time- Which fields each layer may override is itself declared, so a tenant can change a supplier ranking rule but not the PHI disclosure scope.
- Preview: saving a tenant config runs the workflow's simulation suite with the new effective config and shows the metric diff before it can be published.
11. Voice AI platform
The CEO said "one person leads all of voice", across vendor calls, the companion, activations and the workmate, and the Voice JD asks for exactly this pipeline. If the round is voice-focused, the prompt will likely be "design the voice platform" or "extend voice to X". This section covers it end to end, diagram first.
11.1 Where voice shows up, and one runtime for all of it
| Surface | Direction / medium | What's hard about it |
|---|---|---|
| Vendor and office calls | Outbound, phone | IVRs, holds, voicemail, getting to the right desk, extracting facts reliably, not calling too often |
| Activation line | Inbound, phone | Identifying and verifying callers, older callers, handing off to a person, peak volume |
| Companion voice mode | In-app, WebRTC | Natural conversation, health content boundaries, turning requests into cases |
| Workmate | In-app, WebRTC | Screen context, acting through tools safely, not interrupting too much |
The platform move: each surface supplies a call spec (who, why, what to find out, what may be disclosed, persona, limits); one runtime handles telephony, the real-time loop, call control, guards, recording and tracing. Every call ends as the same interaction record the rest of the platform already consumes.
call_spec = {
"party_id": "sup_142", "number": "+13125550142", "direction": "outbound",
"goal": "qualify_supplier", "slots": ["stocks_K0001", "accepts_assignment", "serves_zip_60614", "lead_time_days"],
"disclosure_scope": "no_patient_identifiers", "persona": "mira_assistant_v3",
"opening": { "disclose_ai": true, "disclose_recording": true },
"ivr_hint": "press 2 for orders", "max_minutes": 12, "on_voicemail": "leave_callback_no_phi",
"case_id": "case_123", "idempotency_key": "case_123:seq_88:supplier"
}
11.2 Telephony and media: how audio gets in and out
- Phone calls: a CPaaS (Twilio or similar) or a SIP trunk provides numbers, inbound routing, outbound dialling, recording, status callbacks and media. Media reaches workers either as SIP/RTP into a media server, or as a WebSocket stream (Twilio Media Streams sends base64 μ-law at 8 kHz). Twilio docs
- App voice (companion, workmate) uses WebRTC: wideband Opus audio and the browser's echo cancellation, so recognition is better than on a phone line. A framework with an SFU (e.g. LiveKit) can serve both, bridging SIP calls into the same rooms.
- Caller ID and spam labelling: outbound calls to offices are easily flagged as spam if numbers are unregistered or attestation is poor (STIR/SHAKEN). Use registered, consistent numbers per purpose and a callback number that reaches us. Carrier labelling practices vary; verify with the provider.
- When we're down: the provider's fallback URL routes inbound calls to a static flow (forward to the advocate line or take a voicemail that becomes a task). Twilio 11200
- CPaaS vs own SIP edge: CPaaS first (fast, managed, BAA available on some tiers); own SIP trunk + media servers later for cost and control, at the price of carrier interconnects, attestation and on-call telephony.
11.3 The real-time pipeline
- Cascaded (STT → LLM → TTS), as drawn: each stage swappable, transcripts for free, guards on text before it's spoken, deterministic control possible. The right default for healthcare, where every utterance must be checkable.
- Speech-to-speech models (audio in, audio out): lower latency and better prosody, but harder to guard before speech, harder to inject deterministic control, and transcripts are a side output. Good for the companion's casual voice mode later; risky for calls that disclose or collect PHI. State the trade-off; don't pick a side dogmatically.
- Phone audio is 8 kHz narrowband: choose STT models tuned for telephony; numbers, names and item codes are where errors cost most.
- Turn detection combines VAD silence with a semantic end-of-turn model; give longer patience when the caller is reading out a number or an address, or when they're older. Respond too early and you interrupt; too late and it feels broken.
11.4 Latency budget
| Stage | Typical (approximate) | Levers |
|---|---|---|
| Network + telephony, both ways | ~20–100 ms | Workers in the same region as the media edge and the providers |
| End-of-turn decision | ~200–500 ms | Semantic turn detection instead of a long fixed silence |
| STT final | ~100–300 ms | Streaming STT; start on a stable partial |
| LLM first token | ~200–600 ms | Smaller model for routine turns; cache the stable prompt prefix; short per-phase prompts |
| TTS first audio | ~150–400 ms | Streaming TTS from the first sentence |
| Target, end of speech → first audio | ~0.8–1.2 s | Measure every stage per turn; alert on p95 |
- Hide unavoidable waits: a short acknowledgement ("let me check that") while a tool call runs; a filler after a threshold on slow turns (you built a ~1.5 s filler hedge in your own stack).
- Prefetch at call start: the party brief, case state and call spec are loaded before the first word.
- These figures come from vendor blogs; say "roughly" and prefer numbers you measured.
11.5 Interruptions and barge-in
- Backchannels aren't interruptions: "mm-hmm" or "okay" while the agent speaks should not stop it. A small classifier (or a minimum speech duration plus word check) separates them.
- Real interruption: stop audio immediately (clear the provider's queue), cancel in-flight LLM and TTS work, then truncate the agent's last message to what was actually played (playback marks), so the model doesn't believe it said things the caller never heard.
- Metrics: false barge-in rate (stopped for noise or a backchannel) and missed barge-in rate (kept talking over the caller).
11.6 Call control: who decides what to say
- Code owns the agenda: which slots are still open, when to re-ask, when to give up on a question ("they can't say" is an answer), when to wrap up, when to transfer. This is the converse primitive running live.
- The LLM owns the phrasing: one natural question at a time, acknowledgements, small talk, handling "who is this?"; constrained by the persona and the disclosure scope.
- Per-turn extraction updates slots with evidence quotes as the call goes, so the agent doesn't ask twice and the call can end as soon as the goal is met.
- Guards on every utterance before TTS: no identifiers outside the scope, no dollar figures unless supplied, no medical advice; normalise text first so "forty seven dollars" is caught too.
- Why not a free-form agent on the call? The take-home showed the failure modes: a model that asks three questions at once, hangs up in the same turn it asks a question, or invents an address. Code-owned agendas and guards remove those classes of bug.
11.7 Outbound calls to offices, vendors and payers
| Phase | Detector / mechanism | Learned over time |
|---|---|---|
| Answered by a machine? | Answering-machine detection (provider feature or own classifier on the first seconds) | Which numbers usually go to voicemail at which hours |
| IVR | Speech classification of prompts; match menu options to the goal; send DTMF; fall back to "operator" / "0" | Per-party IVR paths, stored as procedures with success counts |
| Hold | Music/silence/speech classifier; LLM idle; maximum hold time per purpose; accept callback offers | Typical hold time by party and hour → scheduling |
| Person | Open with name, purpose, AI and recording disclosure; converse; ask for the right desk | Who to ask for; what they need first (e.g. the order) |
| Transfer | Detect being transferred; re-introduce briefly | Direct lines that skip the front desk |
| Voicemail | Callback message without PHI; schedule a retry | Whether voicemails ever get returned |
- One call, several cases: the dispatcher can coalesce cases for the same office into one call, within disclosure rules.
- Payer calls can have very long holds; the cheap hold listener keeps cost down, and holds count toward concurrency planning.
11.8 Inbound calls: activations and the patient line
- Caller ID is a hint, not proof. It narrows the lookup; verify identity (e.g. name plus date of birth) before discussing anything personal. HIPAA requires verifying identity and authority of unknown requesters before disclosure. 45 CFR 164.514(h)
- Safety first: urgent symptoms trigger a fixed script and emergency guidance, never generated advice.
- Intent routing into workflows: activation (collect details, consents, create the account, schedule the welcome), a question about an open case (read status from the case), a new request (open a case).
- Warm transfer to an advocate with a short spoken or on-screen summary, so the patient doesn't repeat themselves; after hours, a scheduled callback.
- Peaks: queue briefly with a message, then offer a callback; never let callers sit in silence.
11.9 Speaking with older patients
- Slower speech rate, shorter sentences, one question per turn, plain words ("your share of the cost" rather than "coinsurance").
- Longer end-of-turn patience; tolerate long pauses without jumping in.
- Confirm numbers digit by digit and read addresses back; offer to repeat; say what will happen next and when.
- Caregivers: a second contact with defined permissions; three-way calls when the patient wants them.
- Hearing: offer SMS or a summary in the companion after the call.
11.10 In-app voice: companion voice mode and the workmate
- Same pipeline, better audio (wideband WebRTC), plus screen context: which case or page is open, so "approve this" or "what's happening with my wheelchair?" resolves without a search.
- Tools act through the autonomy gate: spoken "approve" resolves an approval task; sending PHI or committing a patient needs explicit confirmation; every action is audited with the user as the actor.
- Interruption policy for the workmate: speak up only above an urgency threshold; queue the rest for a pause or "what's next?"; learn per advocate from dismissals.
- Companion boundaries: no diagnosis or medical advice; health questions become provider questions (Part 2 workflow) or advocate tasks; urgent symptoms take the safety path.
11.11 Scaling and capacity
- Little's law: concurrent calls = call rate × average duration. 5,000 calls/day over ~8 busy hours ≈ 625/hour; × ~6 minutes ≈ 60 concurrent on average, ~200 at a 3× peak. Holds raise the average duration, so include them.
- Workers: one async session per call; N calls per worker, limited by CPU for audio processing (noise suppression, VAD, resampling) and memory, not by network-bound model calls. Find N with a load test using simulated callers.
- Autoscale on concurrent calls (target ~60–70% of capacity), not CPU; pre-scale for known peaks (Monday mornings, campaign launches). New workers take time to start; spikes arrive in seconds.
- Provider limits: STT, LLM and TTS concurrency caps are part of capacity; the router must know them, and a second provider route should be ready.
- Deploys drain: stop sending new calls to old workers, let active calls finish (with a cap), track dropped calls per release.
11.12 Failure modes
| Failure | What the caller experiences | Mitigation |
|---|---|---|
| STT provider slow or down | Silence, or the agent misunderstands | Fallback STT; "sorry, could you repeat that?" once; then transfer or callback |
| LLM slow | Long pause | Filler at a threshold; fallback model; for scripted turns, a template reply |
| TTS down | Nothing said | Fallback voice; pre-recorded critical lines (disclosure, goodbye) |
| Worker crash | Call drops | The call can't move between processes; checkpoint slots each turn so the case continues; schedule a callback; fallback route for inbound |
| One-way audio / codec mismatch | Caller can't hear us | Detect no inbound speech after our greeting; hang up and retry; alert on rates per carrier |
| DTMF not recognised by an IVR | Stuck in a menu | Try speech ("representative"), then "0"; record the failure against the party's procedure |
| Wrong person / wrong number | Disclosure risk | Confirm we've reached the intended party before any detail; minimum-necessary scope |
11.13 Quality: making voice a number
| Metric | Level | Why |
|---|---|---|
| Task success (goal slots filled correctly) | Call | The point of the call |
| Fact accuracy vs later verification or labels | Call / slot | Wrong facts cost patients money |
| Entity error rate (numbers, names, item codes) | Turn | Overall WER hides the errors that matter |
| End of speech → first audio, p50 / p95 | Turn | What callers feel as "slow" |
| False and missed barge-ins; "can you repeat that" rate | Turn | Conversation quality |
| Hang-up before goal; transfer and escalation rates | Call | Where calls fail |
| Compliance: disclosures made, nothing extra disclosed | Call | Must be 100% |
| IVR success, hold time, answer rate by party and hour | Call | Feeds scheduling and procedures |
- Replay: recorded audio through a new STT model, turn-detection setting or prompt, offline; compare entity accuracy and extracted facts against the gold set, not just transcripts.
- Simulated callers: TTS-voiced personas with accents, line noise, IVRs and difficult behaviour, for load tests and regression before any real call.
- Human review: the call-review team samples calls with a rubric; their labels calibrate any LLM judge and grow the gold set.
- Rollout: shadow (new component runs silently on live audio) → canary by surface or tenant → full, with per-version dashboards.
11.14 Compliance on voice
- Disclosures at the start: that it's an AI assistant and that the call is recorded. Some states require all-party consent to record; disclosing on every call is the simple safe rule. RCFP
- AI voices under the TCPA: the FCC's 2024 ruling treats AI-generated voices as "artificial", so outbound calls to patients need appropriate consent unless an exemption applies (there's a health-care message exemption with conditions). Confirm specifics with counsel. FCC
- Recordings are PHI: encrypted, access-audited, retention policy, providers under BAAs (telephony, STT, TTS, LLM).
- Voicemails never contain PHI; identity is verified before personal details are discussed.
11.15 Build or buy
| Layer | Options | Recommendation |
|---|---|---|
| Telephony | CPaaS (e.g. Twilio) · own SIP trunk + media servers | Buy first; own edge only when cost or control justifies it |
| Real-time framework | Open-source frameworks (e.g. LiveKit Agents, Pipecat) · managed voice-agent platforms (e.g. Vapi, Retell) | A framework you can run and extend; managed platforms are fast to start but limit control over guards, traces and PHI handling |
| STT / TTS | Several vendors with streaming APIs | Multiple providers behind an interface; choose by entity accuracy on your own gold set, latency and BAA terms |
| Call control, guards, evals | — | Build: this is the product and the moat |
Check vendors' current features and BAA terms before naming them as decisions; they change often.
11.16 Your voice experience, mapped honestly
| Topic | What you've built | What you haven't (say it plainly) |
|---|---|---|
| Telephony | A SIP ingress in production: SIP proxy with TLS → media server → bridge into a WebRTC agent framework; identity passed through as headers; transcoding; flood protection | PSTN carrier work: it runs on WhatsApp calling SIP; no STIR/SHAKEN in production |
| Real-time pipeline | Streaming STT and TTS (custom plugin), VAD and a multilingual turn detector, adaptive interruption, two noise-suppression backends, a filler for slow turns, an inactivity ladder to a graceful hang-up | Endpointing and barge-in were configured and tuned, not built from scratch |
| Call control | A deterministic state machine sitting in the LLM's slot in the pipeline, with semantic routing and hybrid classification: code decides, templates speak | — |
| Observability | Per-stage latency histograms and per-turn traces of the whole decision chain | Audio-linked replay and a voice eval harness: designed, not shipped |
| Real-world calls | Code-switched Hindi/English, noisy lines, digit dictation repair, a dropped-call bug traced and fixed | IVR navigation, answering-machine detection, warm transfer (handoff today is a message) |