# AI caller pilot routing — providers, split, redial

Part of the [AI Voice Agent](/docs/modules_handbook/shared/voice-agent/readMe.md) module. Built
2026-10-23 for the planned Yunke (外呼宝) pilot: half of a funnel's leads called through a second
provider, compared with Retell on the same leads in the same weeks.

> **Yunke remains disabled at runtime.** The separate [App caller](/docs/modules_handbook/shared/voice-agent/yunke-app-caller.md)
> is now wired and fake-tested behind an explicit write gate and profile mode. An off or
> unconfigured Yunke arm is skipped there, never moved to Retell. Legacy static-task profiles
> do not silently migrate to this App/Web candidate, which differs from the PDF's official APIs.

## What it does

- **A campaign names its conversation provider** (`ai_call_profiles.provider`, every existing row
  `retell`). A call is routed by the provider of the campaign it is placed under; an unknown or
  not-yet-integrated provider refuses the call and **never falls back to Retell** on its own.
  The one exception is chosen, not automatic: a Yunke phone profile may name a **backup Retell
  profile** (2026-11-10), used only when the line refuses before any phone task exists. See the
  [Yunke console](/docs/modules_handbook/shared/voice-agent/yunke-console.md#backup-retell-profile).
- **A pilot split** hands a share of a campaign's funnel calls to a second campaign. Each funnel
  send is drawn into an arm ONCE and keeps it.
- **A redial policy** rings a missed funnel call again, the same way for every provider.
- **A high-intent alert** tells the team about an answered lead call whose analysis reads high
  intent, through the Notifier.
- **A pilot report** (`voice-agent:pilot-report`) compares the two arms of a split, per lead.

Nothing is split or redialled until an admin sets it: both are null on every existing campaign.
The [routing controls](/docs/modules_handbook/shared/voice-agent/pilot-routing-ui.md) now
save those settings from a control profile's Settings tab without publishing content.

## How it works

### Local integration baseline (2026-10-25)

The twelve pilot commits were ported over the local App/Web result ledger without
merging their unrelated remote baseline. This checkout keeps its existing four-argument
caller contract and Retell default caller ID; per-campaign caller-ID or WhatsApp-channel
changes from the remote baseline were not imported. Only the required nullable
`call_window` column/reader/defer helpers and reserved call-origin tag readers were added.
An explicit profile window always applies; profiles without one keep the existing global
Retell window behavior. Updating the window alone keeps provider content synced and its
hash unchanged. These are profile caps, not a verified one-to-one SIM inventory.

### Provider routing

- `AiCallProfile::PROVIDER_RETELL` / `PROVIDER_YUNKE`; `usesRetell()` treats a row from before the
  column (or an unsaved model) as Retell. `provider_settings` (json) holds a non-Retell provider's
  dialling settings — for Yunke `{task_id, dial_prefixes, daily_cap}`.
- The candidate App route instead uses `{mode: app_single_task, dial_prefixes, daily_cap}`
  plus an explicit same-day call_window (any hours since 2026-11-10). Its per-attempt parent ID is stored on
  the binding, not as a pre-existing task_id or agent_id.
- `isCallable()` = active **and** `providerReady()`: Retell → `isSynced()` (unchanged, and it keeps
  its Retell-only meaning because every Retell screen reads it); App-mode Yunke → explicit
  window, positive cap, market and configured caller. Legacy static-task profiles have no real
  adapter; fake test adapters retain the old task-ID behavior. Unknown providers are never ready.
- `PlaceAiVoiceCall` asks `ConversationalCallerResolver::for($profile->provider)`: Retell → the
  container binding; enabled Yunke → the App adapter (log-only in local without real voice);
  disabled/other providers → `UnavailableConversationalCaller`. The row is stamped with the
  profile's provider. App mode starts without agent/call IDs and the verified deferred receipt
  keeps it pending; Retell defaults are never stamped on another provider's row.
- New refusals: `outside_market` (the number does not start with one of `dial_prefixes` — a phone
  dials from one SIM, so a Hong Kong lead on a Malaysian phone would be an international call; a
  non-Retell line with NO market covers no number at all, while Retell with none covers any),
  `daily_cap` (the line placed `daily_cap` non-refused calls today, local day — counted AND claimed
  under a per-line lock `ai-call-cap:{profile id}`, so two placements at once cannot both read "one
  below the cap"; one that cannot get the lock within 3 seconds does not dial), and
  `provider_unavailable`.
- **Retell stays isolated:** the daily spend fuse (`dailyBudgetExhausted()`) binds Retell calls only
  and counts Retell rows only — a phone's queued calls would otherwise count at Retell's worst case;
  `voice-agent:reconcile` sweeps Retell rows only (it asks Retell, which does not know other
  providers' calls, and its six-hour give-up is not a phone queue's clock); `RetellAgentSync::sync()`
  and `deleteArtifacts()` leave a non-Retell campaign alone, and the profile page's Sync and
  `voice-agent:test-call --profile` (which dials Retell directly) refuse one.
- A Retell campaign's settings hash is unchanged: `canonicalSettings()` adds `provider` only off
  Retell, and `provider_settings`, `ab_split`, `redial_policy` are never part of it.

### Pilot split (`ab_split`)

- `ab_split = {profile_id, pct}` on the CONTROL campaign. `AiCallSplit::resolve()` runs in
  `SendFunnelAiCall` before the calling-window defer: a send with a stored assignment
  (`funnel_automation_sends.meta.ai_call_routing` = arm, control id, chosen campaign, that
  campaign's provider, pct, assigned_at) uses it; otherwise, when the rule's campaign has a split,
  it draws once and stores it. The draw is `crc32("{control id}:{lead id}") % 100 < pct`, and a
  lead's later send under the same control **inherits** the arm of its first one
  (`inherited_from_send_id`) while the split is on — so a pct change mid-pilot never puts one person
  in both arms.
- **Never re-drawn**: the deferred run, the concurrency retry, a redial, a "call me back" click
  (`PlaceFunnelAiCallback` uses `AiCallSplit::profileFor()`), and an admin changing `pct` all keep
  the stored arm. If the assigned campaign has since moved to another provider the send is skipped
  as `routing_changed` (and a callback returns nothing) rather than rung through a different
  provider. A variant that cannot call is skipped there — the lead is not moved to the control.
- The call row carries `meta.ab_arm` and `meta.ab_control_profile_id`.
- **One worker per send**: `SendFunnelAiCall` takes a cache lock `funnel-ai-call:send:{id}` around
  the whole run; a second copy of the job releases itself for 30 seconds and then finds the send no
  longer QUEUED. Before this, two copies could both pass the QUEUED check and each ring the lead.

### Redial (`redial_policy`)

- The PDF's converted-customer stop reads a confirmed `FunnelJourney::STATUS_WON` for
  the **same lead and funnel** before an unsubmitted first call or queued redial. A redial
  stops quietly before policy-removal release; frozen funnel metadata (or its original
  send for legacy rows) defines scope. A win on another product/funnel and an active
  intermediate paid path are not global opt-outs. This read does not close human tasks,
  cancel remote tasks or alter journey state. Untracked historical conversions must be
  excluded/verified by the pilot owner before admission.

- Before an unsubmitted first AI call, the shared job rechecks the original registration
  (exists, unmuted), cancellation and actual session state; genuinely past non-AFTER_ENDED
  rules stop. Zoom live overruns use `Event::live_status`, not the planned end clock.
  No-show calls spare both Zoom joins and confirmed registration attendance. Redials now
  apply those registration/attendance checks too, stopping quietly for person/session
  changes. Already accepted/uncertain phone tasks are recovered without resending and
  are never claimed cancelled by these local checks. See [PDF workflow acceptance](/docs/modules_handbook/shared/voice-agent/yunke-pdf-acceptance.md).

- `redial_policy = {max_attempts, gap_minutes}` — attempts INCLUDE the first call (bounds 2–5 and
  30–1440 minutes, and the chain must finish within the day a chain may run:
  `(max_attempts − 1) × gap_minutes < 1440`, checked by the routing form and `voice-agent:routing`
  via `AiCallRedial::policyFitsChain()`). `schedule()` also refuses to queue a redial that would be
  due after that day, so the miss is final at once instead of a day later. In a split the
  CONTROL's policy governs both arms (`AiCallRedial::policyFor()`), so the two are compared on
  equal terms.
- `AiCallAftermath::settled()` asks `AiCallRedial::schedule()` before the missed effects. It
  redials only a **confirmed miss** of a lead's funnel call (NO_ANSWER / BUSY / VOICEMAIL, not
  refused, with `meta.funnel_automation_send_id`; never payment, AI-rounds, hand-placed or AE
  calls). Pending, failed and refused calls are never redialled, nor is a miss older than
  `MAX_AGE_HOURS` (24 — a backfill replaying old settlements must not ring yesterday's leads).
  Scheduling is a `claimMeta('redial_queued_at')` on the missed row — of the webhook and the
  reconcile sweep, only one queues `RedialAiCall` (delayed by the gap).
- `RedialAiCall` → `AiCallRedial::redial()` under a lock `ai-call-redial:{root uuid}:{attempt}` and
  a duplicate check on `meta.redial_root_uuid` + `meta.attempt` (and on `redial_stopped`, so a
  re-delivered job never acts twice). Right before ringing it re-checks: answered any AI call since
  the chain began (stop), joined the session's webinar (stop), the chain is under a day old (else
  release), the customer is not on another call right now — another row for the same lead or the
  same number still waiting for its outcome, placed in the last 6 hours (else look again in 10
  minutes) — the policy still allows this attempt
  (`--no-redial` stops queued redials too), the send-time conditions `SendFunnelAiCall` applied — the
  session cancelled or moved, or an after-webinar rule's payment condition no longer matching
  (stop); a video-sales-letter lead who has left the slot — no slot registration remains, the same
  test the lead-clicked callback applies (stop); the rule, slot or funnel switched off, or the
  session already over for a non-after-webinar
  rule (release) — the SAME campaign still callable on the SAME provider, and the calling window
  (defer to `nextWindowStart()`). Blocked numbers, paused contact, Retell budget and the line's cap
  are `PlaceAiVoiceCall`'s own guards.
- The [Yunke missed/busy adapter](/docs/modules_handbook/shared/voice-agent/yunke-unconnected.md)
  now connects a strictly verified result to this same chain. Its real reason dictionary
  remains empty: fake-tested support does not enable unknown native outcomes.
- **Only the last miss is final.** While a redial is queued, the journey's "AI call missed" and the
  missed-call WhatsApp wait (`AiCallAftermath::missed()`). A redial that stops for the person's own
  reason (reached, attended, blocked, contact paused) sends nothing; one that cannot ring for any
  other reason (budget, cap, provider, rule switched off, session over, policy removed) **releases**
  the held miss, so nobody loses the WhatsApp to a cap. `meta.redial_stopped` records why. A
  `RedialAiCall` that fails for good releases it too (`failed()` → `abandon()`). An attempt row
  the placement left PENDING with no provider call id and no refusal (it died between creating
  the row and recording the provider's answer; for a phone line, with no claimed task) is not an
  attempt the person received: the retried job closes it as the refusal `never_placed` and
  releases the miss (`attempt_never_placed`), so it stops counting against the line's cap and
  the "on another call" hold. Every release
  first re-asks whether the person may still be contacted (`AiCallRedial::personStopped()`: the
  number blocked here or on WhatsApp, a journey contact hold, the session's registration muted or
  removed) — a stop decided while the redial waited outranks the release and sends nothing.
- `settled()` keeps its old contract on the payment / AI-rounds / hand-placed branches: an exception
  there ends the method — it never falls through to the funnel's webinar-worded missed WhatsApp.
- `AiVoiceCallRepository::mergeMeta()` (and `settle()`'s cost block) merge into the row as it is NOW,
  re-read under a lock, so one settle path cannot erase a claim the other just wrote.

### Explicit spoken contact refusal

`AiCallContactRefusal` reads only customer turns on a completed lead call, including
settlement before a summary arrives. A small, anchored set of explicit Chinese,
Cantonese, English and Malay stop-contact imperatives is supported. AI turns, summaries,
negations, hypotheticals and channel-only requests are not global opt-outs. A Yunke turn
must also have one matching customer span within the recording duration; an overrun is
not evidence of a fully spoken refusal. An explicit customer imperative with uncertain
native timing pauses this call's follow-ups for review without setting a global DNC or
number block. Replay cannot acknowledge that work as complete or send a thanks meanwhile.
The local Yunke view shows a fixed review notice. This is not a general natural-language classifier.

`AiVoiceCallRepository::recordContactRefusal()` rechecks the exact turn/hash under the call
lock, then atomically records the canonical lead `ContactPolicy`, the scoped AI number
block, cancellation of pending contact through `ContactSuppression`, and the source-turn
receipt in call meta. Existing restrictions are never cleared. Replays do not increment
the policy again or fabricate a staff actor. No journey inference/automation flag is enabled.

The call's own refusal receipt also prevents that call's old follow-up after an
administrator later re-enables future contact. No restriction is automatically lifted.

Both providers' next placement/redial already recheck that policy. Final missed handling
and `SendAiCallFollowUp` now recheck it too, including an already queued follow-up. Internal
Discussion history can still be written after genuine customer speech, but no thanks or
hot-lead alert is queued for the opted-out lead. A failed refusal write leaves Yunke's
settlement effect pending; it must not be acknowledged just because analysis is absent.

### High-intent alert (`ai_call.hot_lead`)

- Reads ONLY the standard reading `analysis.custom_analysis_data.intent_level`
  (`AiVoiceCall::intentLevel()` → `high` / `medium` / `low`, case-insensitive; anything else is
  null). A Retell campaign asks for it with an `intent_level` extraction field (enum high / medium /
  low) — that is campaign configuration, no code. Another provider's own labels are translated by
  ITS mapper; nothing here guesses what an "A" or "高意向" means.
- `AiCallAftermath::analyzed()` → `alertHighIntent()` for a COMPLETED, analysed lead call whose
  lead actually spoke (a customer turn — the same evidence rule as the Discussion comment). It runs
  BEFORE the comment's once-only stamp, so an intent that arrives with a later analysis still
  alerts.
- Recipients are whoever subscribed to the event on Manage → Notifications — no names in code. The
  message carries a lead's name, phone and call summary company-wide, so the event requires
  `VIEW_LEADS_ALL` and is **off by default** (subscribe on purpose); no throttle. Once per call via
  `claimMeta('hot_lead_alert_at')`; when the Notifier queued nothing, or building the alert threw,
  the claim is released so a later analysis pass can retry, and `analyzed()` returns false. On Retell
  that later pass is the next webhook/reconcile touch; on Yunke the result ledger reads the false
  and leaves `analysis_handled_at` unset, so the watch's effects branch calls `analyzed()` again on
  later passes until the alert is queued — only the alert is retried, the comment and thanks are
  not repeated. Fail-soft.

### Pilot report (`voice-agent:pilot-report`)

- `AiCallPilotReport::build($control, $from, $to)` — read-only. Population: the funnel sends
  ASSIGNED under that control (`meta.ai_call_routing.control_profile_id`) whose `assigned_at` is in
  the window; their calls: every `ai_voice_calls` row carrying one of those sends' ids (first call,
  redials, "call me back"), created up to the window end.
- **Per lead**: a lead's attempts collapse into that lead. The stages stay apart — leads assigned →
  call attempts (rows) → refused before ringing → provider call ID observed (distinct from task acceptance/import;
  Retell has it at placement, a phone line only once a result is bound) → phone tasks accepted /
  unknown / rejected / unclaimed (the phone line's own ledger; `n/a` for an arm without one) → rang
  (a confirmed outcome) → awaiting outcome → leads whose phone rang → leads connected.
- **Two connect rates, each with its denominator in the row label**: `÷ rang` = leads connected ÷
  leads whose phone rang at least once (how the call does once it rings; unknown when none rang,
  and **withheld while any call still awaits an outcome** — a phone line reports connected results
  only, so its unanswered calls stay awaiting and the row would read 100% by construction),
  and `÷ assigned` = leads connected ÷ leads assigned to the arm, rung or not (how many it actually
  reached — refusals, a phone's queue and unanswered calls all count against it; a real 0% when
  leads were assigned and none connected, unknown only when none were assigned). The command
  prints both definitions under the table.
- **Unknown is never zero**: a completed call with no transcript at all is "unknown", not "did not
  speak"; durations, costs and start times the provider has not reported are counted apart (cost
  is "known total + N unknown", and "unknown" when no cost is known at all); intent counts only
  calls the lead spoke on, with "intent unknown" for leads who spoke but have no reading;
  attendance is joined / not joined / unknown, for the session each
  send was about — unknown when there is no webinar for it or its scheduled window had not ended by
  the window end.
- Pending App tasks without a provider call ID still count as unknown cost; the table labels
  observed call IDs separately from task import/acceptance. Cost per non-refused local attempt
  is shown only when **all** those attempts have a known cost; a partial known sum is not a
  comparable mean. No price or zero is invented for Yunke. Queue wait requires a start at or
  after local row creation; missing/backward timestamps are unknown, while a genuine zero wait
  stays zero. The report regression file covers both boundaries.
- **Crossover leads**: leads with a call through a provider other than their arm's — should be 0;
  anything else means the comparison is contaminated. `Calls by provider` shows what was actually
  used, and `Leads in both arms` (should be 0) is printed under the table. Human callers are not in
  the ledger; their column is filled by hand.

## Known limitations

- **A Retell concurrency refusal on a redial is not retried** — it releases the held miss (the
  WhatsApp goes out) instead of trying again ten minutes later as `SendFunnelAiCall` does. A retry
  would need the refused attempt row excluded from the duplicate check.
- **A redial job lost from the queue** (never run, never failed) leaves its miss held; there is no
  sweep for `redial_queued_at` with no attempt yet.
- The pilot report loads its population into memory and checks attendance per lead — fine at pilot
  volume (hundreds of leads), not built for a full-funnel history.

## Reference usage

```bash
# show a campaign's routing
php artisan voice-agent:routing my-webinar-call
# half of NEW leads to a second campaign; every send keeps the arm it was drawn into
php artisan voice-agent:routing my-webinar-call --split-to=my-webinar-call-yunke --pct=50
# end the pilot (leads already drawn keep their arm)
php artisan voice-agent:routing my-webinar-call --no-split
# redial a missed funnel call: 3 attempts in all, 2 hours apart
php artisan voice-agent:routing my-webinar-call --redial-attempts=3 --redial-gap=120
php artisan voice-agent:routing my-webinar-call --no-redial
# compare the arms (local dates; default: from the first assignment to now)
php artisan voice-agent:pilot-report my-webinar-call --from=2026-11-02 --to=2026-11-08
```

A save of ONLY routing keys through `AiCallProfileRepository::update()` keeps the campaign synced,
callable and its knowledge entries untouched; any other save behaves as before (clears
`synced_at`). Never write `ab_split` / `redial_policy` through the profile form's full payload.

## Related files

- [AiCallProfile.php](/src/VoiceAgent/AiCallProfile.php) — `PROVIDERS`, `ROUTING_FIELDS`, `REDIAL_*`,
  `usesRetell()`, `providerReady()`, `providerAgentId()`, `coversNumber()`, `dailyCap()`,
  `abSplit()`, `redialPolicy()`
- [ConversationalCallerResolver.php](/src/Common/VoiceAgent/ConversationalCallerResolver.php) ·
  [UnavailableConversationalCaller.php](/src/Common/VoiceAgent/UnavailableConversationalCaller.php)
- [PlaceAiVoiceCall.php](/app/Actions/PlaceAiVoiceCall.php) — routing, `outside_market`, `daily_cap`,
  the Retell-only budget
- [Support/AiCallSplit.php](/src/VoiceAgent/Support/AiCallSplit.php) ·
  [SendFunnelAiCall.php](/app/Jobs/Automation/SendFunnelAiCall.php) (lock + resolve) ·
  [PlaceFunnelAiCallback.php](/app/Actions/PlaceFunnelAiCallback.php)
- [Services/AiCallRedial.php](/src/VoiceAgent/Services/AiCallRedial.php) ·
  [Jobs/VoiceAgent/RedialAiCall.php](/app/Jobs/VoiceAgent/RedialAiCall.php) ·
  [Services/AiCallAftermath.php](/src/VoiceAgent/Services/AiCallAftermath.php) (`missed()`,
  `alertHighIntent()`) · [config/notify.php](/config/notify.php) (`ai_call.hot_lead`)
- [AiVoiceCallRepository.php](/src/VoiceAgent/Repositories/AiVoiceCallRepository.php) — `claimMeta()` /
  `releaseMeta()` · [AiCallProfileRepository.php](/src/VoiceAgent/Repositories/AiCallProfileRepository.php)
  — the routing-only save
- [SetAiCallRouting.php](/app/Console/Commands/SetAiCallRouting.php) `voice-agent:routing`
- [Support/AiCallPilotReport.php](/src/VoiceAgent/Support/AiCallPilotReport.php) ·
  [ReportAiCallPilot.php](/app/Console/Commands/ReportAiCallPilot.php) `voice-agent:pilot-report`
- Migrations: `2026_10_23_100000_add_provider_to_ai_call_profiles`,
  `2026_10_23_110000_add_routing_to_ai_call_profiles`
- Tests: [ProviderRoutingTest](/tests/Feature/VoiceAgent/ProviderRoutingTest.php) ·
  [AiCallSplitTest](/tests/Feature/VoiceAgent/AiCallSplitTest.php) ·
  [AiCallRedialTest](/tests/Feature/VoiceAgent/AiCallRedialTest.php) ·
  [HotLeadAlertTest](/tests/Feature/VoiceAgent/HotLeadAlertTest.php) ·
  [AiCallPilotReportTest](/tests/Feature/VoiceAgent/AiCallPilotReportTest.php) · fixtures in
  [BuildsFunnelAiCalls](/tests/Concerns/BuildsFunnelAiCalls.php)

## Where the Yunke adapter plugs in later

- **Placement (import)**: replace the `UnavailableConversationalCaller` branch in
  `ConversationalCallerResolver::for()` with a `YunkeConversationalCaller` whose `call()` imports the
  lead into `providerAgentId()` (the task) and returns an id. It must refuse — not fall back — when
  disabled, and a dev box needs a number allow-list (this box runs on live credentials).
- **Results**: a receiver that settles `provider = yunke` rows through
  `AiVoiceCallRepository::settle()` / `recordAnalysis()` and then `AiCallAftermath::settled()` /
  `analyzed()` — the redial and the follow-ups then work unchanged. Turns must be written as
  `AiVoiceCallTurn` rows (`ROLE_USER` for the customer) or the aftermath's "the lead never spoke"
  guard skips the comment and the thanks WhatsApp.
- **Timeouts / silence**: Yunke rows are excluded from `voice-agent:reconcile`; they need their own
  sweep with a timeout longer than a phone's queue.
