Interview prep · Mira Mace · Part 2 of 3

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

WORKFLOW RUNTIME Companion patient chat · voice Mira agent advocate asks Enterprise API referrals · rules Inbound world calls · faxes · SMS Normalise + safety triage urgent symptoms first Identify patient + party registry match Correlate belongs to an open case? Classify → workflow else bounded planner (L1) Event log per case, append-only Scheduler generic decide() Autonomy gate risk · level · policy Outbox + timers durable, idempotent Context builder packets for each step Primitives converse · obtain · consent … Human plane approvals · exceptions Dispatcher + executors capacity · batching Knowledge plane parties · facts · memory LLM gateway routing · guards · BAAs Eval + observability traces · replay · gates Channels → world voice · fax · SMS · portals open case needs approval
The whole platform. Read top to bottom: requests come in, the runtime decides, primitives act through channels, and every result flows back into the case's event log.
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 · gates

1. 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

New mention name in a transcript · fax header · caller ID Normalise phone → E.164 · address standardised Strong ID match? NPI · verified phone or fax Same party attach to it Block + score candidates same ZIP / area code · name similarity · shared numbers Score above threshold attach + record evidence Ambiguous human review task: candidates side by side Merge / split = events reversible, audited yes no high unsure
Resolving a new mention to a party: strong identifiers first, scored candidates second, a human for anything ambiguous.

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.

1.2 What a party profile contains

Identity + contact names · NPI · numbers · hours · timezone Capability facts stocks K0001 · accepts assignment · serves ZIP Behaviour statistics answer rate by hour · promise- kept rate · hold time PARTY PROFILE Lakeshore Home Medical Equipment Procedures IVR path · who to ask for · preconditions Relationships locations · parent org · payers in network Tenant overlay contracted · preferred · private notes
A party profile is six layers, each with its own source and update rule.
LayerExamplesWhere it comes fromStored as
Identity & contactNames, NPI, numbers, addresses, hours, timezone, holidaysDatasets, calls, documents, humansRows in parties, party_identifiers, party_locations
Capability factsStocks K0001; accepts assignment; serves ZIP 60614; takes plan X; accepts new Medicare patients; typical delivery 2–3 daysExtracted from calls and documentsTyped facts with evidence, source and freshness
Behaviour statisticsAnswer rate by hour and weekday; median hold time; callback rate; promise-kept rate; document turnaround; which channel gets resultsComputed from interaction events (no LLM)Aggregates in party_behavior_stats, recomputed incrementally
ProceduresIVR path ("press 2, then 4 for orders"); "ask for the DME desk"; "they need the order before quoting a date"; best fax number for ordersCall traces that succeeded; lessons promoted by humansparty_procedures with success counts
RelationshipsParent organisation; locations; which payers it's in network with; which providers refer to itDatasets, documents, case historyEdge tables (graph later)
Tenant overlay"Contracted supplier for tenant A"; preferred; do-not-use; internal notesTenant config, advocatesparty_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

Call ends transcript + events Extractor (LLM) observations with evidence quotes Validator schema · quote in their turns · entails value Merge policy source rank · recency · conflicts Facts (current view) with freshness Ungrounded kept for audit, never used Contested re-verify: task or piggy-back question FactChanged event open cases re-check Interaction events dialled · answered · hold · promise Behaviour stats streaming aggregates pass fail conflict
Agents write claims (observations); a deterministic merge decides what becomes a fact. Behaviour statistics come straight from interaction events, with no LLM.
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)

1.4 How agents read a profile: the party brief

Step needs a brief purpose = qualify supplier Context builder deterministic assembly · token budget Party brief call plan · known · stale · watch out Agent (LLM) holds the call Facts + as-of + source Behaviour stats best window to call Procedures IVR path · ask for Recent summaries no other patients' PHI
The agent never queries tables: the context builder assembles a purpose-shaped party brief with provenance on every item.

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
}

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

Facts semantic, structured Behaviour statistics Procedures IVR paths, preconditions Relationships care team, networks Episodes interaction summaries, past cases Documents SOPs, payer policies Postgres facts · stats · procedures · edge tables Graph DB (later) projection for multi-hop queries pgvector + keyword index metadata filters: tenant · patient · party Key lookup party + field Traversal neighbourhood of the case Hybrid search + rerank similar situations edge tables project
Each kind of memory goes to the store that fits how it is queried. Postgres stays the system of record; the graph is a rebuildable projection.
KindExampleStoreRetrieved 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 statisticsAnswer rate by hour; promise-kept rate; fax turnaroundPostgres aggregatesKey lookup; used as features by scheduling and ranking
ProceduresIVR paths; "ask for the DME desk"; "they need the order before quoting"Postgres rows with success countsKey lookup by party + purpose
RelationshipsPatient → care team; supplier → payers in network; office → parent system; provider → suppliers they usually send orders toEdge tables in Postgres; a graph DB when traversal needs growNeighbourhood 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 metadataSemantic search with hard filters (tenant, patient, party)
Documents and guidanceSOPs, payer policies, coverage rules, Medicare publications, tenant playbooksVector index + keyword index; source of truth in object storageHybrid 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.
"I'd start with Postgres for facts, stats and edges, and pgvector for episodes and documents, because it's one system to secure and isolate by tenant. A graph database is a projection I'd add when the multi-hop questions become central, fed from the same events so it can always be rebuilt."

2.3 How behaviours are learned

Interaction events every call, fax, reply Streaming aggregation no LLM Behaviour stats most trusted Successful call traces the path that worked Count successes N wins → active Procedures demoted on failures Batches of interactions per party or workflow Reflection (LLM) candidate lessons + evidence IDs Validate by counting candidate → active → retired Used as hints + features context builder · scheduler · ranking Hard rule? only if a human promotes it
Three ways behaviour is learned, from most to least trusted. LLM lessons are only hints until counting confirms them.

Three sources, in order of trust:

  1. 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.
  2. 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.
  3. 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 + preferences plan · language · timezone · contact window Consents contact offices for me · recording · SMS Caregiver what they are allowed to hear PATIENT Mrs. Martinez Care team cardiologist → office party · PCP → office Episodes companion summaries; clinical text verbatim Cases open + closed, with event logs
Patient memory is a small graph around the patient, strictly scoped to their own cases.

2.5 The context builder: how memory reaches an agent

Step spec converse(Sunrise, obtain order, Martinez) 1 · Key lookups party brief · allowed patient fields · case state 2 · Graph expansion Martinez → Dr. Chen → Sunrise 3 · Semantic recall filtered by tenant · party · type · date 4 · Budget fixed slots per source 5 · Provenance every item tagged + packet logged Context packet replayable LLM call via the gateway
The context builder: what the step must know comes from key lookups; semantic search only adds hints, within a fixed budget.

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

2.6 Risks in a learning memory, and the controls

RiskControl
Memory poisoning: one confused receptionist's wrong answer spreads to every caseObservations vs facts; source ranking; contested state; re-verification; human vetting for high-impact fields
Stale lessonsLessons carry evidence counts and dates; re-validated periodically; retired on contradiction
PHI leaking across patients or tenantsHard metadata filters at query time; row-level security; episodes about parties stored de-identified; tenant overlays never shared
Right to delete / retentionEvery memory item points to its source record; deleting a patient deletes or de-identifies derived episodes and embeddings
Embedding model changesEmbeddings versioned; re-index in the background; queries pinned to one version until the cut-over
Retrieval quality drifts silentlyA 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

Workflow timers retry · verify a promise Self follow-ups ScheduleFollowUp(at, cancel_if) Recurring schedules CPAP every 90 days Human SLAs approval due · task ageing timers table due_at · reason · action · cancel_on · status Timer poller due rows, highest priority first Case wakes decide() on the current state
All scheduled work, whatever its origin, becomes a row in one timers table. Nothing waits in memory.
KindExampleCreated by
Workflow timersRetry a supplier in 2 business hours; verify the clinic's promise at 10:00 tomorrow; hold expiresThe 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 schedulesCPAP supplies every 90 days; monthly check-in call; annual plan reviewA schedule entity that spawns a case each cycle
Human-facing deadlinesApproval SLA; task ageing; escalation if untouched for a dayThe human plane

3.2 Choosing the time: needs × availability × likelihood × capacity

Earliest allowed policy gap since last attempt ∩ Party calendar hours · holidays · timezone (DST-safe) ∩ Tenant calling window e.g. 8am–8pm recipient local ∩ Patient window only if the patient is involved Score each slot answer rate (shrunk to type average) − delay + jitter → timer row deadline steps take the earliest slot
Choosing when to call: intersect the allowed windows, then pick the slot most likely to get an answer.
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

3.3 The dispatcher: capacity, priority and batching

Ready actions outbox rows, due now Priority deadline · patient risk · age Capacity checks channel · party · tenant · model budget Over capacity stays queued; timer slides; enrichment shed first Coalesce same party within 30 min → one call Channel executor leased, idempotent full ok
The dispatcher turns due actions into work while respecting capacity, and merges calls to the same party.
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

3.4 Self-scheduled follow-ups, and cancelling them

ScheduleFollowUp verify order @ Thu 10:00 · cancel_if OrderReceived Timer: pending a row in the database Due → fired passes through decide() first Call the clinic action → outbox Cancelled OrderReceived arrived first No-op decide() sees the order already received needed event race lost
A follow-up the workflow schedules for itself, and the two safety nets that stop it firing needlessly.
# 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)

3.5 Recurring schedules

Schedule RRULE · next_run_at · timezone Poller next_run_at reached Spawn case idempotency key = schedule + period Compute next run written back to the schedule
Recurring care: a schedule spawns a fresh case each cycle, exactly once.
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

4.2 The mechanics, in one picture

ONE TRANSACTION (milliseconds) Take case lease one writer per case Load snapshot + events rebuild state decide() pure, versioned definition Append + outbox + timers events · actions with keys · timers Executor claims row SKIP LOCKED Already done? check interactions by idempotency key Perform effect call · fax · SMS (minutes) Append result event CallEnded · FaxDelivered … no wakes the case
Deciding is short and transactional; doing is slow and asynchronous. Results come back as events that wake the case.
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

Decide in a transaction Commit events + outbox rows Executor runs the effect Effect done call placed / fax sent Result recorded event appended Crash before commit lease expires; the same decision is re-made Crash after commit outbox row still pending; an executor picks it up Executor dies mid-call provider callback or timeout → CallEnded(dropped) Died before recording idempotency-key lookup finds it; no second call Deploy during a long wait nothing in memory; rows persist; version pinned
Where a crash can happen (left), and what recovers it (right).
Crash pointWhat happens
Worker dies before committing a decisionNothing 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 runsThe outbox row is pending; an executor picks it up.
Executor dies mid-callThe 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 itOn 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 waitNothing is in memory; the new code reads the same rows. The case stays pinned to its workflow version.
Timer poller down for an hourTimers 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 reducerAfter 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 overPoint-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

Advocate approves task resolved Webhook fax delivered · call ended · SMS reply Deadline timer no reply by due time Event appended to the case log ApprovalGranted · FaxDelivered · WaitExpired Case wakes: decide() on the new state a two-week wait cost nothing but a row
Every external wait ends in an event, and every wait has a deadline with a typed outcome.

4.5 Versions and long histories

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

Params from the workflow definition Track state folded from events primitive.next(state, params, now) pure · typed · unit-tested Act(action) → autonomy gate DueAt(t) → timer Done(value) → joins may fire Failed(reason) → typed escalation
Every primitive is a pure function from its state, its parameters and the time to one of four results.
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

Blocked window · consent · rate limit → DueAt No answer / voicemail → DueAt(retry) Transfer / safety stop → human Plan open questions · scope · brief Precheck Dial / send In conversation guards on every utterance Extract observations + quotes Validate grounded? entailed? Done typed outcome Ungrounded re-ask next time ok fail
The converse primitive's state machine. Every exit is a typed outcome.
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)

5.3 Obtain (a document or answer from a party)

Register expectation party · patient · document type Phone ×3 learned: start with fax for some parties Fax request verify after 1 business day Human task nothing worked Document arrives matched by intake Validate six order elements · expected item code Received track done Mismatch e.g. K0003 vs K0001 → escalation broken valid invalid fax arrives
Obtain: climb a channel ladder until the document arrives, then validate it.

5.4 Commitment

Made who · what · due_by · evidence Waiting timer at due_by + grace Kept verified by an event or a check Broken next rung of the ladder Party stats promise-kept rate updated verified due passed
Commitment: a promise is tracked until it is independently verified.
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_rate

5.5 Consent

Not asked Explained terms stated plainly Understood? checked, not assumed Agreed quote recorded in consents Declined typed outcome Agreed without understanding re-explain once, then human yes no unclear
Consent: agreement only counts when the patient understood what they agreed to.
Text version
NOT_ASKED ─▶ EXPLAINED(terms) ─▶ UNDERSTOOD? ─┬─▶ AGREED (evidence: quote) ─▶ recorded in consents
                                              ├─▶ DECLINED
                                              └─▶ AGREED_WITHOUT_UNDERSTANDING ─▶ re-explain or human

The 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

Request prompt@v · schema · PHI flag Route task type → model PHI? only BAA-covered providers Call timeout · fallback chain Infra error timeout / 429 / 5xx → retry or next provider; never a business outcome Validate schema invalid → retry with the error as feedback Guards no new identifiers · no figures · no advice Result + trace tokens · latency · cost
Every model call goes through one gateway, so routing, PHI rules, retries and tracing live in one place.
FunctionDetail
Prompt registryPrompts are versioned artifacts with an owner and an eval suite; a step references prompt_id@version.
RoutingPer task type: fast model for live conversation, stronger model for extraction or planning; fallback chain across providers.
PHI-aware providersRequests 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 outputEvery non-conversational call has a schema; invalid output is a failed attempt, retried with the validation error as feedback.
GuardsOutgoing 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 taxonomyTimeouts, 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.
BudgetsTokens and cost per case, per tenant, per workflow; exceeding a budget escalates rather than silently continuing.
TracingEach 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

Voice Fax SMS Email Portal browser automation Interaction record party · direction · outcome · transcript or document · disclosures · idempotency key Primitives converse · obtain · notify
Every channel produces the same interaction record, so primitives never care how a party was reached.
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)

Call spec party · goal · questions · scope · persona Place call status callbacks to us IVR phase detect menu · learned path · DTMF Hold phase cheap listener, LLM idle Human on the line STT → turns → LLM → TTS · guards · disclosures Call ends transcript + recording stored CallEnded event → extraction → observations Voicemail policy: callback message, never PHI human returns
An outbound call's lifecycle. The LLM only runs when a human is on the line.
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 → extraction

7.3 Fax

Webhook fax received Store restricted access OCR Classify per page order · records · decision · bill Extract identifiers name · DOB · provider · item code Match expectations open cases waiting for this Attach → event 2+ identifiers agree Human matching task ambiguous · unknown patient · mixed pages confident otherwise
Inbound fax: page-level classification and two-identifier matching before anything is attached automatically.

7.4 SMS, email, portals

8. The human plane in detail

Created by autonomy gate · escalation · human step Open packet: summary · evidence · proposal Routed own advocate → skill → general queue Claimed in the inbox or via the workmate SLA ladder remind → reassign → supervisor Resolved approved · edited · rejected Label stored diff → evals → autonomy Event wakes the case overdue
A human task's lifecycle. The case keeps running its other tracks while a person handles this one.
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)

9. Observability and replay

Every step and turn traced Trace decision + why · packet id · prompt@v · model · latency Case replay new workflow definition Step replay logged packet → new prompt / model Call replay recorded audio → new STT / turn settings Diff → release gate metrics per version
Traces make three kinds of replay possible, and replays gate releases.
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

10. Configuration resolution

Platform default Workflow definition @ pinned version Tenant config @ pinned version Patient preference only patient-settable fields Preview on save simulation suite with the new config Allowed-override rules + schema e.g. a tenant may change ranking, never disclosure scope Effective value what the step uses
Configuration resolves through four layers; each layer may only override the fields it's allowed to.
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

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

Vendor + office calls outbound · IVRs · holds Activation line inbound · new customers Companion voice mode patients · in-app Workmate advocates · in-app Call spec party · goal · questions · disclosure scope · persona · limits Voice runtime telephony + WebRTC · real-time pipeline · call control · guards · traces Interaction record → extraction → case events same shape as every other channel
Every voice use case at Mira is a call spec handed to one shared voice runtime.
SurfaceDirection / mediumWhat's hard about it
Vendor and office callsOutbound, phoneIVRs, holds, voicemail, getting to the right desk, extracting facts reliably, not calling too often
Activation lineInbound, phoneIdentifying and verifying callers, older callers, handing off to a person, peak volume
Companion voice modeIn-app, WebRTCNatural conversation, health content boundaries, turning requests into cases
WorkmateIn-app, WebRTCScreen 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 network patients · offices · vendors · payers CPaaS or SIP trunk numbers · caller ID attestation · recording Media bridge SIP or media WebSocket (8 kHz μ-law) Companion / workmate app browser or mobile WebRTC (SFU) Opus · echo cancellation in the client Voice worker one async session per call Same worker type same pipeline, wideband audio Fallback route if our webhook fails: forward or voicemail
Two ways audio reaches the runtime: phone calls through a carrier or CPaaS, app audio through WebRTC.

11.3 The real-time pipeline

Audio in 20 ms frames Noise suppression + resample VAD is someone speaking? Streaming STT partials → finals Turn detection silence + semantic end-of- turn Call controller state · slots · what to ask next LLM (streamed) phrases the next utterance Guards no new identifiers · no figures Sentence chunker first sentence ASAP Streaming TTS Audio out marks track what was played
One conversational turn in a cascaded pipeline. Everything streams; nothing waits for a full stage to finish.

11.4 Latency budget

StageTypical (approximate)Levers
Network + telephony, both ways~20–100 msWorkers in the same region as the media edge and the providers
End-of-turn decision~200–500 msSemantic turn detection instead of a long fixed silence
STT final~100–300 msStreaming STT; start on a stable partial
LLM first token~200–600 msSmaller model for routine turns; cache the stable prompt prefix; short per-phase prompts
TTS first audio~150–400 msStreaming TTS from the first sentence
Target, end of speech → first audio~0.8–1.2 sMeasure every stage per turn; alert on p95

11.5 Interruptions and barge-in

Agent is speaking TTS audio queued Caller speech detected VAD during playback Backchannel? 'mm-hmm', 'okay' → keep talking Real interruption clear queued audio · cancel LLM + TTS Truncate history to the last played mark New turn listen to what they said no
Barge-in: stop talking fast, and remember only what the caller actually heard.

11.6 Call control: who decides what to say

Call spec goals: K0001 in stock? assignment? ZIP? lead time? Slot state filled · unknown · refused, with evidence Turn policy (code) next goal · re-ask · wrap up · transfer LLM utterance one question, natural phrasing Guards → TTS Caller replies Per-turn extraction slot updates + quotes
Call control: code decides what the call still needs; the LLM decides how to say it; extraction fills slots every turn.

11.7 Outbound calls to offices, vendors and payers

Dialling caller ID · ring timeout Answered by? human · IVR · voicemail IVR menu detection · learned path · DTMF Hold music detector · LLM idle Person disclose AI + recording · converse Transfer? to the right desk / to an advocate Wrap-up confirm · callback number · goodbye Voicemail callback message, no PHI Call ended transcript · recording · outcome IVR person machine
Outbound call phases. Each phase has its own cheap detector; the LLM runs only when a person is on the line.
PhaseDetector / mechanismLearned 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
IVRSpeech 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
HoldMusic/silence/speech classifier; LLM idle; maximum hold time per purpose; accept callback offersTypical hold time by party and hour → scheduling
PersonOpen with name, purpose, AI and recording disclosure; converse; ask for the right deskWho to ask for; what they need first (e.g. the order)
TransferDetect being transferred; re-introduce brieflyDirect lines that skip the front desk
VoicemailCallback message without PHI; schedule a retryWhether voicemails ever get returned

11.8 Inbound calls: activations and the patient line

Call arrives number dialled · caller ID Lookup caller ID → patient / party (a hint, not proof) Verify identity e.g. name + DOB before any PHI Intent activate · question · reschedule · urgent Urgent symptoms fixed script · emergency guidance Workflow activation · case update · new case Warm transfer to an advocate with a spoken summary After hours / busy callback scheduled · message human
Inbound: know who's calling, verify before discussing anything personal, then route by intent.

11.9 Speaking with older patients

11.10 In-app voice: companion voice mode and the workmate

User speaks push-to-talk or open mic WebRTC session low-latency, wideband Voice pipeline STT · turns · LLM · TTS Screen context case in focus · page state Tools read case · approve task · draft message Autonomy gate confirm before acting Audit actor = the user
In-app voice (companion, workmate): the same pipeline, plus what's on the user's screen and tools that act.

11.11 Scaling and capacity

New call inbound or dispatched Call router region · capacity · priority Worker registry free slots, heartbeat TTL Worker pool N calls per worker (CPU- bound audio) Providers STT · LLM · TTS concurrency limits Autoscaler target utilisation on concurrent calls Deploys drain: no new calls, finish active No headroom queue briefly → callback / voicemail
Scaling voice: route each call to a worker with headroom; scale on concurrent calls, not CPU.

11.12 Failure modes

FailureWhat the caller experiencesMitigation
STT provider slow or downSilence, or the agent misunderstandsFallback STT; "sorry, could you repeat that?" once; then transfer or callback
LLM slowLong pauseFiller at a threshold; fallback model; for scripted turns, a template reply
TTS downNothing saidFallback voice; pre-recorded critical lines (disclosure, goodbye)
Worker crashCall dropsThe 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 mismatchCaller can't hear usDetect no inbound speech after our greeting; hang up and retry; alert on rates per carrier
DTMF not recognised by an IVRStuck in a menuTry speech ("representative"), then "0"; record the failure against the party's procedure
Wrong person / wrong numberDisclosure riskConfirm we've reached the intended party before any detail; minimum-necessary scope

11.13 Quality: making voice a number

Live calls recorded with consent Per-turn trace audio offsets · STT · latency · decisions Scored outcomes task success · fact accuracy · compliance Dashboards + alerts p95 latency · hang-ups · escalations Gold set labelled calls: entities, outcomes Replay harness recorded audio → new STT / prompts / turn settings Simulated callers TTS personas · accents · noise · IVRs Release gate no regression on key metrics label
Voice quality as a number: traces linked to audio feed replay, simulation and dashboards; changes are gated on them.
MetricLevelWhy
Task success (goal slots filled correctly)CallThe point of the call
Fact accuracy vs later verification or labelsCall / slotWrong facts cost patients money
Entity error rate (numbers, names, item codes)TurnOverall WER hides the errors that matter
End of speech → first audio, p50 / p95TurnWhat callers feel as "slow"
False and missed barge-ins; "can you repeat that" rateTurnConversation quality
Hang-up before goal; transfer and escalation ratesCallWhere calls fail
Compliance: disclosures made, nothing extra disclosedCallMust be 100%
IVR success, hold time, answer rate by party and hourCallFeeds scheduling and procedures

11.14 Compliance on voice

11.15 Build or buy

LayerOptionsRecommendation
TelephonyCPaaS (e.g. Twilio) · own SIP trunk + media serversBuy first; own edge only when cost or control justifies it
Real-time frameworkOpen-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 / TTSSeveral vendors with streaming APIsMultiple 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

TopicWhat you've builtWhat you haven't (say it plainly)
TelephonyA SIP ingress in production: SIP proxy with TLS → media server → bridge into a WebRTC agent framework; identity passed through as headers; transcoding; flood protectionPSTN carrier work: it runs on WhatsApp calling SIP; no STIR/SHAKEN in production
Real-time pipelineStreaming 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-upEndpointing and barge-in were configured and tuned, not built from scratch
Call controlA deterministic state machine sitting in the LLM's slot in the pipeline, with semantic routing and hybrid classification: code decides, templates speak—
ObservabilityPer-stage latency histograms and per-turn traces of the whole decision chainAudio-linked replay and a voice eval harness: designed, not shipped
Real-world callsCode-switched Hindi/English, noisy lines, digit dictation repair, a dropped-call bug traced and fixedIVR navigation, answering-machine detection, warm transfer (handoff today is a message)
"I've owned the whole real-time path in production, from SIP signalling to the dialogue controller. The parts I haven't shipped are PSTN-specific: navigating other people's IVRs, voicemail detection, warm transfer. Here's how I'd build them on top of the same pipeline."