# Yunke — funnel → queue → App task → timed collection loop

Part of the [AI Voice Agent](/docs/modules_handbook/shared/voice-agent/readMe.md).
Added 2026-10-27 on dev-yc. Offline engineering and fake-response tests only: no task was
created, no phone dialled, no gate enabled, nothing pushed or deployed.

## What it does

Closes the gap between the two routes that already work — the bounded CLI self-test
([yunke-self-test.md](/docs/modules_handbook/shared/voice-agent/yunke-self-test.md)) and the
console-managed sessions — and the business path a real lead takes:

```
funnel welcome / reminder / VSL rule
  → FunnelAutomationSend (QUEUED)                 src/Event/FunnelAutomationSend.php
  → SendFunnelAiCall::forRule() → queue lane      app/Jobs/Automation/SendFunnelAiCall.php
  → worker runs handle()                           lock, QUEUED check, Yunke recovery, guards
  → PlaceAiVoiceCall::run()                        market / block list / cap / window
  → YunkeConversationalCaller → YunkeAppTaskSubmit one POST aiCallOut/save, claim first
  → voice-agent:yunke-watch → YunkeCallWatch       ≤20 bindings, one results page + one detail
  → YunkeAppResultIngest::collectWeb()             taskId → subTaskId → callActionId
  → YunkeAppCallBindingRepository::apply()         settle, turns, summary, analysis, duplicate
```

One thing changed in code. Every dispatcher now builds the job through
`SendFunnelAiCall::forRule($rule, $sendId, $fallbackConnection)`, which puts a **Yunke App
campaign's** send on its own lane — `services.yunke_app_write.queue` (`YUNKE_FUNNEL_QUEUE`)
on the `redis-ai` connection — the same shape as AI 2 Rounds' round 1 lane, but a separate
key: on dev-yc the AI Rounds lane (`ai-rounds`) was found holding unrelated, billable AI 2
Rounds jobs that a one-shot test worker would have drained first. Unset — production — the
job keeps the lane the caller chose (default for a welcome, `redis-broadcast` for
reminders/VSL), so nothing moves there. Why it matters on an isolated dev box: the phone-task claim is committed
**before** the HTTP send ([YunkeAppTaskSubmit.php](/src/VoiceAgent/Services/YunkeAppTaskSubmit.php)
`claimCreate` → `post`), so a worker without network burns the attempt as `create_unknown`
with no task behind it — and the retry never resends, by design. The send must therefore
only ever be picked up by a process that can reach Yunke.

## How it works

### Gap classification (dev-yc, 2026-10-27)

| Finding | Kind | Where |
| --- | --- | --- |
| Yunke funnel sends landed on the default / `redis-broadcast` lanes, which YC's `PrivateNetwork=yes` workers consume | defect for isolated boxes | fixed: `SendFunnelAiCall::forRule()` + `YUNKE_FUNNEL_QUEUE`, the three dispatch sites |
| The AI Rounds lane `ai-rounds` on YC held two unprocessed AI 2 Rounds jobs (a round brief, a project suggestion) | finding | a shared lane cannot be drained one job at a time for Yunke; hence the dedicated key |
| YC workers and scheduler have no network | configuration, deliberate | `peta-yc-queue@.service`, `peta-yc-scheduler.service`: `PrivateNetwork=yes`, `RestrictAddressFamilies=AF_UNIX`; the scheduler runs a heartbeat-only `SafeConsoleKernel` |
| `voice-agent:yunke-watch` is scheduled only by the production Kernel | configuration | `app/Console/Kernel.php` — on YC run it by hand or with a user timer (below) |
| A send deferred past its window re-dispatches itself to the next window start, next day | existing behaviour, needs teardown | pausing the campaign (or the rule) makes that run skip `missing_config`; gates off refuse placement |
| No remote pause/cancel endpoint | missing, vendor | phone-side stop only; the task's own `endTime` is the window end |

### Offline acceptance — `tests/Feature/VoiceAgent/YunkeFunnelLoopTest.php`

Real dispatcher, real `handle()`, real placement/submitter/watch/collector/writers on the
guarded test database; HTTP faked with `Http::preventStrayRequests()`; queue, mail,
notifications and the Notifier mocked and asserted silent. 9 tests / 95 assertions:

1. A funnel with ONLY an AI-call welcome rule queues one `SendFunnelAiCall` on
   `redis-ai` / the configured Yunke lane; its real handle makes exactly one create request with the
   session headers, one recipient, `redialCount=0`, the campaign's period and the rule-selected
   scene rendered from the registration's variables into customer `otherInfo`; a re-delivered job
   recovers the claim without a second request.
2. The watch binds `taskId → subTaskId → callActionId`, settles the call (29 s, 3 turns,
   summary, verified high intent) in the test database; `collectWeb()` on the same binding
   returns `duplicate` with an identical snapshot.
3. A transport timeout leaves `create_unknown`; neither a retry nor the watch sends again.
4. An authentication rejection fails the send once (`task_create_rejected`) and is never retried.
5. An unverified not-connected reason is held, with no guessed outcome.
6. Allowlist, block list and daily cap refuse before any request.
7. A paused campaign skips; a closed 20-minute sub-window defers (next day, same lane) and
   the deferred job skips once the campaign is paused — no revival.
8. With the controls off, the job skips, the watch returns `disabled`, and nothing is sent.
9. Lane choice: Yunke → its lane, Retell → caller's lane, unset key → unchanged, and a
   configured AI Rounds lane never captures a Yunke send.

Not covered offline, by nature: a separate worker process actually reaching Yunke over the
network, Redis delivery/visibility timing, the vendor's dial count, the phone. Those remain
for the authorized live run.

### Dev-box run configuration (YC) — templates, nothing installed

Isolation already in place: database `peta_yc_dev`, YC's own Redis Unix socket (DB 0 queues,
DB 1 cache), six network-less workers, heartbeat scheduler. For a test, `.env` names the
lane — `YUNKE_FUNNEL_QUEUE=yunke` — which **no worker on YC consumes** (the `ai` worker reads
`ai,evaluation` only), so a Yunke funnel send waits there until a networked process takes
it. There is no config cache on this site, so the line takes effect on the next request and
the next CLI call; removing it is the rollback.

**One-shot worker, in the operator's own shell (has network, like the CLI self-test):**

```sh
cd /home/yc/peta
php artisan queue:monitor redis-ai:yunke                # expect 0 before the test
php artisan queue:work redis-ai --queue=yunke --once --tries=1 --timeout=90 --no-interaction
```

`--once` processes one job and exits; nothing is daemonised, no unit is changed, no network
policy is touched. The job's own lock, `retryUntil` and `maxExceptions` still apply.

**Timed collection for one bounded window (no scheduler):**

```sh
for i in $(seq 1 7); do php artisan voice-agent:yunke-watch; sleep 180; done
```

Seven runs, three minutes apart, covers a 20-minute observation. Each run is bounded by the
watch itself (≤20 bindings, one page + one detail per binding, lease released at the end,
auth failure stops the batch).

**Standing user timer (optional, needs `loginctl enable-linger yc`, i.e. an admin):**

```ini
# ~/.config/systemd/user/peta-yc-yunke-watch.service
[Service]
Type=oneshot
WorkingDirectory=/home/yc/peta
ExecStart=/usr/bin/php artisan voice-agent:yunke-watch --no-interaction

# ~/.config/systemd/user/peta-yc-yunke-watch.timer
[Timer]
OnCalendar=*:0/10
Unit=peta-yc-yunke-watch.service
[Install]
WantedBy=timers.target
```

This runs in the user session (networked) and only ever calls the watch command, which is
inert while any of its three gates is off. Do not add the production `schedule:run` here.

**Start / stop / rollback:**

- Start: `.env` `YUNKE_FUNNEL_QUEUE=yunke`; console — allowlist, read-only check, enable
  reads → results → watch → calling; campaign Allow locally; then trigger the funnel send
  and the one-shot worker.
- Stop (local): console **Pause calling & processing**, campaign Pause, rule toggle off.
  `php artisan queue:monitor redis-ai:yunke` must read 0; a delayed job that remains skips
  on its day because the campaign is paused — do not clear or replay the lane. Remove the
  `.env` line last, or a later delayed job would land on the default lane instead.
- Stop (phone): the operator ends the task in the Yunke App; the task's `endTime` is the
  campaign window end, so it cannot run past the sub-window.
- Rollback of the code change: revert the `forRule()` / lane-key commits; production
  behaviour is unchanged either way because `YUNKE_FUNNEL_QUEUE` is unset there.

### What a live funnel run still has to prove

A real worker process on the lane reaching Yunke; the send row moving QUEUED → SENT from
that process; the watch run from a separate process settling it; and the same phone-side
evidence as the CLI test. The production window stays 10:00–21:00; a test campaign uses a
sub-window of at most 20 minutes inside it so the vendor task expires with the test. The
CLI self-test's early-morning exception is typed and console-only — a funnel job never
carries it (`YunkeConversationalCaller.php` refuses a persisted marker).

## Related files

- `app/Jobs/Automation/SendFunnelAiCall.php` — `forRule()`, lane choice, recovery, deferral.
- `app/Actions/DispatchFunnelWelcomeAction.php`, `app/Console/Commands/RunFunnelAutomationReminders.php`, `app/Console/Commands/RunFunnelVslTriggers.php` — the three dispatch sites.
- `config/services.php` (`yunke_app_write.queue`) — the lane key; `app/Jobs/AiRounds/Concerns/RunsOnAiRoundsLane.php` — the sibling AI Rounds lane it is modelled on.
- `tests/Feature/VoiceAgent/YunkeFunnelLoopTest.php` — the offline loop.
- [yunke-app-caller.md](/docs/modules_handbook/shared/voice-agent/yunke-app-caller.md), [yunke-watch.md](/docs/modules_handbook/shared/voice-agent/yunke-watch.md), [yunke-console.md](/docs/modules_handbook/shared/voice-agent/yunke-console.md) — the pieces the loop joins.
