care-loopTake-home walkthroughGitHub ↗

Where the loops meet.

The caseEleanor Martinez, 72, Original Medicare Part B, needs a standard manual wheelchair (K0001). This is how the engine gets it to her, and what happens at tryMatch.

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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

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

03Three loops, one meeting point

Fig. 2
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 --> T
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 --> T

The 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:

Fig. 3
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 confirmed
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 confirmed

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

Interactive · Hand-off sequence
Select a row or event to see its log lines and code. Open on its own page
Fig. 4
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
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

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

Interactive · Failover sequence
Select a row or event to see its log lines and code. Open on its own page
Fig. 5
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 supplier
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 supplier

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

Interactive · Which loop is ready second
Select a row or event to see its log lines and code. Open on its own page

Order paperwork stalls and fax delays

Fig. 6
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
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

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.