care-loop gets Eleanor Martinez a K0001 wheelchair without a person on the case. Two independent loops, suppliers and the written order, meet at one function, tryMatch. Its guards make the hand-off, the failover, and every race between the loops come out the same way.
Code: shanky1506/care-loop @ 0ef3da9. npm test passes 18/18, and all 5 scenarios end as the README says, both offline and live on openai/gpt-6-luna.
01The problem
Eleanor Martinez is 72, on Original Medicare Part B with no supplemental plan. Her PCP, Dr. Chen, saw her 3 days ago and gave a verbal order for a standard manual wheelchair (HCPCS K0001). No written order has been submitted and no supplier has been contacted.
For a care advocate, getting her the chair takes these steps:
- Find a supplier. Call down a 12-name directory that lists only name, phone, and address. Ask each one: new Medicare patients? K0001 in stock? Accept assignment? Deliver to her area? How soon? What's her 20%? Many don't answer, and many say no.
- Get the written order. Fax Dr. Chen's office a pre-filled standard written order, then keep following up. Requests get lost, sit unsigned, or come back for the wrong item.
- Match and book. Once both exist, send the signed order to the supplier, get a delivery date, and check the billing code matches the order. Otherwise the claim is denied.
- Keep Eleanor informed. Tell her the date and what she'll owe, and get her to confirm she'll be home.
Most of this work is waiting, following up, and checking. The hard part is noticing a stall early and knowing the next move. That's what the system automates.
02Code decides, the model reads
Mermaid source
flowchart TB
subgraph WORLD["Mock world (mock.ts)"]
direction LR
SUP["Supplier reps"]
PCP["PCP office: phone + fax"]
ELE["Eleanor: SMS"]
end
READ["LLM reads (llm.ts): text to fixed fields + verbatim quote"]
CHECK["Code checks (rules.ts): quote is theirs, no negation, signature, date stated"]
ENGINE["Engine (engine.ts): timer queue, 3 loops, tryMatch"]
TPL["Template texts"]
BRIEF["LLM writes the handoff brief"]
HUMAN["Care-advocate inbox"]
WORLD -- "transcripts, faxes, replies" --> READ
READ -- "facts or null" --> CHECK
CHECK -- "verified facts, else unknown" --> ENGINE
ENGINE -- "fixed-script calls, faxes, follow-ups" --> WORLD
ENGINE --> TPL -- "SMS" --> ELE
ENGINE -- "escalate" --> BRIEF --> HUMAN- Every decision is code in src/rules.ts and src/engine.ts, running on a simulated business-hours clock (Mon to Fri, 09:00 to 17:00 Chicago).
- The model only reads. It turns transcripts and faxes into strict structured output, each field with a verbatim quote. Code then checks the quote is in the other party's words, not our script, and that a "yes" doesn't come from a line that says "not". Anything that fails becomes
unknown, which means a call-back or an escalation. - The model never writes to Eleanor. All five texts are templates filled from case state. The model's only free text is the escalation brief, which a person reads.
- The mock world (src/mock.ts) plays the suppliers, the PCP office, fax, SMS, and delivery from fixed hidden facts per scenario. The engine never reads those facts.
03Three loops, one meeting point
Mermaid source
flowchart TB
subgraph SL["Loop 1: suppliers"]
C["Call supplier (fixed script)"] --> Q{"qualify"}
Q -- "unclear or no answer: retry" --> C
Q --> QS["Qualified: primary + backup"]
end
subgraph OL["Loop 2: written order"]
R["Fax request"] --> K["orderCheck +1, +3, +5 days"]
K -- "not received: resend" --> R
K --> V["Order valid"]
end
QS -- "calls" --> M{"tryMatch: both ready?"}
V -- "calls" --> M
M --> H["Hand off, 1-day deadline"]
H -- "no date" --> F["Fail over"]
F -- "backup" --> M
H -- "callback" --> B["Booked: date and code backed"]
subgraph PL["Loop 3: patient"]
T["Text Eleanor, asks YES"] --> CF["Confirmed"] --> D["Delivered"]
end
B --> TThe one sentence to land: the supplier loop and the order loop never call each other. Each calls tryMatch whenever it makes progress, and tryMatch acts only when both are ready. The patient loop's only input from them is "delivery booked."
Why that shape: the loops move at different paces. Supplier calls go every 15 minutes; order follow-ups go every 1 to 2 business days. Neither should wait on the other, and whichever finishes second triggers the hand-off.
All handlers run one at a time from a single sorted timer queue, so there are no concurrent writes. Stale timers are never cancelled. Each one checks a token, such as match.supplier or order.docsReceived, and returns if it no longer applies.
04tryMatch and the match states
src/engine.ts:444-456, with the log line trimmed:
private async tryMatch() {
if (this.order.status !== "valid" || this.match.status !== "waiting") return;
const [pick, ...rest] = this.candidates();
if (!pick) return; // supplier loop is still working (or already escalated)
this.match.status = "handed_off";
this.match.supplier = pick.id;
this.match.tried.push(pick.id);
// log: "Match: valid K0001 order + <pick> … Backup: <rest[0]>"
const transcript = await this.world.handOff(pick.id, this.now, this.order.code!);
const id = pick.id;
this.at(addBusinessHours(this.now, POLICY.supplierConfirmWithinBusinessHours),
"delivery date deadline", () => this.supplierDeadline(id));
}Three guards, then three state writes, then the hand-off:
- Order valid. Set only by
validateOrderpassing on a faxed order. - Match waiting. It can only hand off once at a time. A second qualifier arriving later is a no-op.
- A candidate exists.
candidates()is the qualified suppliers not yet inmatch.tried, ranked by soonest delivery, then directory order (src/rules.ts:29-30). The backup is simply the next candidate. Nothing is reserved. - State is written before the call. Anything that runs later sees
handed_offand this supplier's id. - A yes is not a booking. A deadline is armed for 8 business hours, and it carries the supplier id so it does nothing once the match has moved on.
Mermaid source
stateDiagram-v2
direction LR
waiting --> handed_off: tryMatch
handed_off --> scheduled: backed date and matching code
handed_off --> waiting: silent at deadline, backup exists
handed_off --> escalated: code mismatch, date unclear, unreadable
waiting --> escalated: no supplier left
scheduled --> delivered: delivery day and Eleanor confirmeddelivered is reached only through a booking backed by the rep's own words and Eleanor's yes. Every other exit from handed_off either fails over or goes to a person.
05The hand-off, step by step
This is the realistic scenario, run live on openai/gpt-6-luna. Three suppliers don't pick up, 2 aren't taking new patients, 1 is out of stock, 1 is outside her area, and 2 qualify. The order is signed on the second follow-up. The run delivers with no escalations and makes 23 model calls, 11 by the system and 12 by the mock.
Mermaid source
sequenceDiagram
participant SL as Supplier loop
participant OL as Order loop
participant M as tryMatch
participant H as Halsted
participant L as LLM + checks
participant E as Eleanor
Note over SL,M: Mon 10:30
SL->>M: Halsted qualified (3 days)
Note right of M: order not valid, return
Note over SL,M: Mon 11:00
SL->>M: Belmont qualified (5 days), supplier loop done
Note right of M: order not valid, return
Note over OL,M: Thu 10:00
OL->>M: order valid (K0001, NPI, signature in fax)
Note right of M: all 3 guards pass
M->>H: fax signed order, call to schedule
M->>M: arm deadline: date within 8 business hours
Note over M,H: Thu 12:00
H-->>M: callback: "Tuesday, December 8 … bill under K0001"
M->>L: extract date, code, quote
L-->>M: 2026-12-08, K0001, quote is the rep's, month+day+weekday agree
M->>E: delivery_booked template, asks YES
E-->>M: "Yes, that's fine. I'll be home."
Note over M: Tue 12/08 13:00: delivered, case closed- Steps 1 and 2:
tryMatchis called twice and does nothing. That's the design working, not wasted work. - Step 3: the order loop finishes second, so its call makes the hand-off.
- Step 8: the date is accepted only because the rep said "December 8", with the day next to its month, "Tuesday" matches 2026-12-08, and the date is within 30 days (src/rules.ts:184-199). The billing code must be said by the rep and equal the order's code, or the claim would be denied (src/engine.ts:496-507).
- Step 9: $5.68 is the supplier's quoted 20% share. The model never produces a number Eleanor sees.
06Failover
The silent-supplier scenario: the fastest supplier says yes, then never calls back.
src/engine.ts:469-482, the end of supplierDeadline, trimmed:
s.status = "silent";
this.match.status = "waiting";
this.match.supplier = null;
if (this.candidates().length) return this.tryMatch(); // backup exists
if (this.suppliers.some((x) => x.status === "not_called" || x.status === "retry")) {
this.supplierLoop = "running"; // no backup: back to the list
return this.supplierTick();
}
this.match.status = "escalated"; // nobody left: a person
return this.escalate("Chosen supplier went silent and no backup is left", …);Failover is a state reset plus one more tryMatch call. There's no separate failover path to test. The silent supplier stays in match.tried, so it can never be picked again. Before marking a supplier silent, the deadline makes one check-in call; if the supplier answers, it gets one more business day, once (src/engine.ts:462-468).
Mermaid source
sequenceDiagram
participant M as Engine (tryMatch, deadline)
participant LS as Lakeshore (2 days)
participant W as Windy City (4 days)
participant E as Eleanor
Note over M: Tue 10:00, order valid
M->>LS: hand off (soonest), backup Windy City
LS-->>M: "Got it, yes. We'll call you back today."
M->>M: arm deadline Wed 10:00
Note over M,LS: no callback all day
M->>LS: Wed 10:00 deadline: check-in call
LS-->>M: no answer
Note right of M: Lakeshore silent, match back to waiting
M->>W: tryMatch again: hand off, backup none
W-->>M: Wed 12:00 callback: Tuesday, December 8, K0001
M->>E: delivery_booked template
E-->>M: confirms, delivered Tue 12/08
LS--)M: (if it called late) ignored: not the active supplierEleanor only hears about a supplier once a date is booked, so she never learned about Lakeshore.
The known gap: a dropped supplier is never told to cancel. Its late callback is ignored (src/engine.ts:488), but in real life two deliveries could happen. The fix is a cancel call on failover.
07Edge cases
Race between the loops
tryMatch can be reached first from either loop. The view switches between the two orderings on one axis.
- Suppliers first (
realistic): twotryMatchcalls return on Monday, and the order loop's call acts on Thursday 10:00. - Order first: an extra offline run, not one of the five scenarios. ChicagoLand (4 days) and Belmont (2 days) answer only on their third try, and the order is signed on the first follow-up. The order is valid at Tue 10:00 with no candidate, so
tryMatchreturns. ChicagoLand qualifies the same minute, andtryMatchhands off to it. Belmont, the faster one, qualifies an hour later and becomes the backup. - Why it's safe: handlers run one at a time from one queue, so the guards are read and written with no interleaving. Two qualifiers can't both be handed the order.
- The trade-off: a valid order matches the first supplier available rather than waiting for the fastest. I chose speed over the best possible pick.
Order paperwork stalls and fax delays
Mermaid source
stateDiagram-v2
direction LR
requested --> valid: validateOrder passes
requested --> requested: wrong once, correction requested
requested --> escalated: 3 follow-ups, wrong twice, no correction, unreadable fax| Case | What the system does | Result |
|---|---|---|
Lost request (lost-order) |
Follow-ups on Tue, Thu, and Mon each hear "never received" and resend at once: 4 faxes in all (src/engine.ts:377-386) | Escalated Mon 12/07 09:00 with a brief. The suppliers are already lined up |
Unsigned, sitting in the queue (realistic) |
Logs a nudge, follows up on the [1, 2, 2] business-day ladder |
Signed on follow-up 2 |
| "Signed, faxing now", but no fax | Arms a 4-business-hour fax deadline. If nothing arrives, it calls again at once, or escalates if the ladder is used up (src/engine.ts:372-376, 389-394) | No scenario stays silent here; the timer is armed in every signed run |
Wrong item (wrong-order) |
Dr. Chen signs K0003. validateOrder names both problems, and a correction request goes out with a 1-business-day watchdog (src/engine.ts:426-439) |
Corrected K0001 arrives the same afternoon; delivered Fri 12/04 |
| Wrong twice, or the fax can't be read | Escalates. An unreadable fax never becomes a "correction" request (src/engine.ts:407-412) | A person reads it |
While the order is stuck, the supplier loop keeps running and tryMatch keeps returning. A stall in one loop never blocks the other.
08What's open, what's next
- The tests prove control flow, not extraction. Offline, the model is stubbed with the mock's answer key. The number that matters is the false-yes rate on real transcripts.
- Failover doesn't cancel the dropped supplier.
- A confirm reply isn't checked for negation. "Yes I can't be home", classified as confirm, would mark her confirmed.
- The billing code passes if the rep says it anywhere in the call.
Next: an extraction eval of about 50 hand-labeled noisy transcripts that measures field accuracy and false yeses per model. After that: a durable workflow engine, real voice, fax, and SMS adapters behind the same Inbound interface, and a care-advocate inbox that hands a case back to automation.
—Likely questions
Why not let one loop call the other? Then one loop owns the timing of the other. With tryMatch as the only meeting point, either can finish first and the result is the same.
What stops two hand-offs? The match.status === "waiting" guard, plus one queue running one handler at a time.
Why keep a backup before the order is even signed? "Said yes, then went silent" is a known failure. With a live backup, failover costs one call instead of restarting the directory.
Why are stale timers not cancelled? Each timer checks its own token and returns. There's no cancel bookkeeping to get wrong, and a late callback is handled the same way.
What if the model is down? read returns null and each caller decides: an unread supplier call is retried like a missed call, and an unread fax or scheduling call goes to a person. A step that throws is logged with its stack and escalated, and the tests fail on it.