# Yunke — bounded result watch and pending effects

Part of the [AI Voice Agent](/docs/modules_handbook/shared/voice-agent/readMe.md).
Built 2026-10-25. Engineering tests use synthetic HTTP and the guarded test database.
No runtime gate was enabled and no vendor request, call or notification was sent.

## What it does

`voice-agent:yunke-watch` processes up to 20 existing Yunke call bindings using the
existing Web Cookie reader and explicit-ID collector. It can recover committed pending
effects and report queues that need review. It never submits a task, logs into the App,
guesses an association or turns elapsed time into a missed call. Recording copies have
their own default-off queue workflow; the result reader does not fetch audio.

The scheduler runs every ten minutes only when **all three** of `YUNKE_WATCH_ENABLED`,
`YUNKE_WEB_READ_ENABLED` and `YUNKE_APP_RESULTS_ENABLED` are true. Each defaults false.
`YUNKE_APP_WRITE_ENABLED` is deliberately independent: stopping new calls must not
prevent draining existing tasks. `YUNKE_APP_AFTERMATH_ENABLED` controls follow-ups;
`YUNKE_WATCH_ALERTS_ENABLED` separately controls internal notifications. Both remain off.
`YUNKE_RECORDING_COPY_ENABLED`, also off, independently allows an additional bounded
20-copy local drain after result checks, scoped to the existing company/user. Its queue
leases recover lost dispatches; failures/changed sources stay held without login or URL
guessing. See [recording copies](/docs/modules_handbook/shared/voice-agent/yunke-recordings.md).

## How it works

### Frozen submission evidence

The pre-send claim stores `call.meta.yunke_submission` atomically with the request hash:

- `claimed_at_ms`: client claim timestamp, before the eventual send.
- `timezone`, `scheduled`, `start_ms`, `end_ms`, `days`, `periods`: the actual submitted
  schedule, excluding recipients, task names and credentials.
- `accepted_at_ms`: first client observation of an accepted response with a literal
  task ID. It is not the vendor's dial/import timestamp or a delivery guarantee.

The first acknowledgement is immutable on response replay. Later profile edits never
rewrite these facts. A valid result preserves the namespace when it settles the call.
Old bindings without this evidence are still eligible for explicit result collection,
but cannot establish a queued-call silence interval. No evidence is backfilled from
today's profile settings.

### Bounded reconciliation

The shared 15-minute cache lease and scheduler overlap guard prevent concurrent sweeps.
Use a shared atomic-lock cache when deploying multiple workers. Candidates are restricted
to the configured, case-sensitive company/user and matching Yunke call UUID/provider:

- Unsettled pending/in-progress calls, including ambiguous creation for diagnostics —
  until they are parked for review (see *Aging and operator closure* below).
- Accepted calls missing their first analysis for 24 hours after verified settlement.
- Ready but unhandled effects, only while their separate gate is enabled.

Null/oldest `last_checked_at` is served first, with a hard limit of 20 bindings. Each
accepted candidate reads at most one 30-row result page and one detail; there is no
page loop, refresh or network retry. The collector's single-task, single-recipient,
single-attempt and explicit-ID requirements still apply. Fully analyzed settled calls
need no repeat read. Late first analysis cannot replace turns or reset settlement time.
After 24 hours, missing analysis remains visibly unknown and needs explicit review;
the automatic watch does not read it forever.

Reserved/unknown/rejected creation is held, without HTTP or resubmission. Watch
observations save only `last_checked_at` and a bounded safe `last_check_reason`; their
repository cannot change identity, result stamps or lifecycle state. Business/auth,
transport and malformed-response exceptions stop the remaining network batch, return
`status=error` with a safe reason, and make the command exit 1. An auth failure never
becomes an empty result. A failure that is one row's own (a storage error, an unexpected
shape) is recorded as `unexpected_error` on that row with a safe warning (binding ID and
exception class only), counted under `errors`, and the batch continues; its transaction has
already rolled back, so the row stays unsettled and is read again on a later turn. The run
still ends `status=error`, so the command exits 1 and the failure stays visible.

Pending shared aftermath is attempted before a late-analysis read. An expired remote
session therefore need not strand already committed effects. Fully analyzed/aged calls
can drain effects without HTTP; a failed effect remains pending with its original
durable stamps. `effects_only` counts attempts, not guaranteed delivery. Shared effects
retain their existing crash/idempotency limitations; this adds no exactly-once promise.

### Aging and operator closure

An unsettled row does not keep a batch slot forever. After one more read, the watch parks
it (`review_required_at`, `review_reason`) when an accepted task is a full day past its
frozen window end (`window_expired_unsettled` — the phone cannot dial it after the window),
or when a reserved/unknown/rejected claim is a day old (`claim_unconfirmed_aged` — nothing
automatic can change it). Parking settles nothing and guesses no outcome: the call keeps
its status and stage label, still counts as awaiting outcome in the pilot report, and shows
a `review_label`. An explicit `collectWeb()` can still settle a late result, after which the
row re-enters the analysis/effects branches as usual. The `review` counter reports parked
rows per run. Without this, every never-connected task stayed in the 20-per-run rotation,
so a week of normal volume pushed a new task's polling interval to hours.

`voice-agent:yunke-close-unplaced {call uuid} --confirm` is the operator's closing step for
an attempt whose task creation was never confirmed: a pending Yunke call whose claim is
reserved, unknown or rejected, or that has no claim at all. It records the refusal
`yunke_task_unconfirmed` (so the row leaves every cap, queue and watch count), stamps
`closed_by_operator`, and triggers no missed-call message, redial or vendor request. It
refuses an accepted task, which may still return a result, and does nothing without
`--confirm`. Use it only after verifying on the vendor backend that no task runs for the
attempt; it is a bookkeeping decision, never evidence about the phone.

### Queue review, without an invented timeout

Only an accepted, unresolved call with the producer's supported same-day/all-week,
single-period 10:00–21:00 schedule can contribute to a silence notice. The grace is
30 minutes from the latest of the frozen start, claim and first acknowledgement.
The current instant must be inside the frozen date range and period. Missing evidence,
unknown creation, future starts, expired windows and idle profiles cannot trigger it.
For example, a task submitted at 20:55 with a 21:00 end is not assumed to queue until
10:00 next day. It remains unresolved for review and can still receive a late result.

One newly verified settlement for the same owner/profile in the preceding 30 minutes
suppresses the notice. Duplicate polling and late analysis do not refresh that clock.
`ai_call.yunke_silent` is opt-in, permissioned by `view-calls`, scoped per profile and
throttled by the existing Notifier for 7200 seconds. Its text asks for session/queue/device
review; it does not diagnose a hardware outage. No lead phone or transcript is included.
Recipients subscribe separately in Notifications; this task changed no subscriptions.

This revises the original T4 plan's proposed 24-hour automatic FAILED timeout. Real
expiry/cancellation and non-answer semantics remain unverified. Closing an uncertain
task could invite a duplicate call or misleading WhatsApp, so no timeout runs aftermath,
redial or missed follow-up. A real pilot still needs the vendor's supported statuses,
queue ordering, expiry/stop proof, long-session behavior and approved alert delivery.

## Reference usage

The consumer is [WatchYunkeCalls](/app/Console/Commands/WatchYunkeCalls.php), registered
by the normal command loader and scheduled in Kernel. With all gates off it returns
`{"status":"disabled"}` before database/cache/network work. After an independently
approved deployment and session provisioning, the same command produces only sanitized
counts/status; do not enable runtime gates as part of an offline test.

[YunkeWatchTest](/tests/Feature/VoiceAgent/YunkeWatchTest.php) supplies synthetic accepted
tasks and responses. It covers the disabled writer/result drain, explicit result binding,
late analysis, case-sensitive ownership, batch fairness, session failure, pending effects,
frozen schedule/acknowledgement, old/expired/missing evidence and unknown creation.

## Related files

- [YunkeCallWatch](/src/VoiceAgent/Services/YunkeCallWatch.php), [WatchYunkeCalls](/app/Console/Commands/WatchYunkeCalls.php), [Kernel](/app/Console/Kernel.php) — bounded service, CLI and gated schedule.
- [YunkeAppCallBindingRepository](/src/VoiceAgent/Repositories/YunkeAppCallBindingRepository.php), [YunkeAppCallBinding](/src/VoiceAgent/YunkeAppCallBinding.php) — frozen evidence and transactional observations.
- [Watch migration](/database/migrations/2026_10_25_110000_add_watch_fields_to_yunke_app_call_bindings.php) — nullable observation time/reason; no production migration was run.
- [Web result contract](/docs/modules_handbook/shared/voice-agent/yunke-web-results.md), [App binding contract](/docs/modules_handbook/shared/voice-agent/yunke-app-results.md), [Notify usage](/docs/modules_handbook/shared/notify/readMe.md) — reused readers, mapper and side effects.
- [services.php](/config/services.php), [notify.php](/config/notify.php), [.env.example](/.env.example), [phpunit.xml](/phpunit.xml) — independent default-off gates and opt-in event.
