# Yunke App — explicit bindings and result ingestion

Part of the [AI Voice Agent](/docs/modules_handbook/shared/voice-agent/readMe.md).
Built 2026-10-25 against the separately authorized S2 task sample, APK 2.0.20.

## What it does

Persists the local call UUID, verified company/user, returned task ID and independently
verified subtask/callActionId. Collects one explicitly bound result and folds a supported
completed recording into `ai_voice_calls` and its turns. Duplicate snapshots do not
replace turns or repeat handled aftermath; a first late summary can arrive separately.

`YUNKE_APP_RESULTS_ENABLED=false` disables collection and ingestion before database or
HTTP access. `YUNKE_APP_AFTERMATH_ENABLED=false` independently leaves follow-up work
pending. Both remain off by default; no runtime environment file was changed. App reads
also require the existing `YUNKE_APP_READ_ENABLED` configuration.

The result processor itself sends no task and adds no public endpoint, command or scheduler.
A separate default-off [Web watch](/docs/modules_handbook/shared/voice-agent/yunke-watch.md)
now calls its Web collector and pending-effect drain; it never schedules the App login path.
A separate default-off [App caller/submitter](/docs/modules_handbook/shared/voice-agent/yunke-app-caller.md)
now links placement to this ledger; runtime routing remains disabled. Results do not discover
IDs by guessing or enable a live pilot. Applied/duplicate results can now offer a call to
the separately default-off [private recording-copy workflow](/docs/modules_handbook/shared/voice-agent/yunke-recordings.md).
That queue claim waits for commit, keeps its own source/token/failure state and never
changes call/aftermath outcomes. Reader methods still fetch metadata/transcripts only.

## How it works

### Creation and explicit binding

- `YunkeAppCallBindingRepository::create()` takes nested `yunke_app_call_binding`
  input: ai_voice_call_id, company_code and user_id. It requires an unrefused PENDING
  Yunke call without a provider call ID, and freezes that row's existing UUID.
- `claimCreate()` accepts only an unchanged descriptor from `YunkeAppTaskAdapter`:
  the verified identity and exactly one recipient matching the local call. It durably
  changes reserved to create_unknown **before** any eventual send. Only the caller
  that receives true may send. There is no reset/retry path after a timeout or crash.
- `recordCreateResponse()` parses the supplied response, storing only an accepted
  literal task ID or a clear rejection. A success without an ID stays unknown.
  A task is unique within the company/user scope: batch-task sharing is unsupported.
- `bind()` requires explicit company_code, user_id, task_id, sub_task_id and
  call_action_id. It cannot move an existing binding to another call. Scoped SHA-256
  keys enforce uniqueness without MySQL collation changing case-sensitive ID meaning.
  Phones, times, names and notes never generate an association.

The App's taskDetailPage child ID and result-list per-call ID have different meanings.
S2 originally linked them through native upload payloads. A later read-only Web probe
verified an explicit cloud source: Web taskDetailPage returns taskId, child id and
per-call callId together, with aiRawResult.callActionId equal to callId. The separate
[`collectWeb()` path](/docs/modules_handbook/shared/voice-agent/yunke-web-results.md)
now consumes that source behind disabled flags; this App collector does not invent a
link from the App results page. Each redial needs a new local attempt and a new task/binding.

### Bounded collection and supported outcomes

`YunkeAppResultIngest::collect($bindingId, $reader)` requires a complete persisted
binding, then calls `YunkeAppReadClient::readCallResult($taskId, $callActionId)`:

1. One normal identity discovery/login sequence, with existing strict identity checks.
2. Results page 1 / size 30; require exactly one matching per-call ID and exact taskId.
   No match returns not_found_on_requested_page, not proof the call does not exist.
3. History page 1 / size 30; match only that exact per-call ID. No row leaves analysis
   pending. Duplicate matches, foreign identities and authentication errors fail explicitly.
4. The exact recording-detail getter, including the echoed callId and identity checks.

There are five requests on the complete path, one login, no automatic pagination,
re-login, token refresh or recording fetch. **A fresh App login was verified to
invalidate the phone's existing token.** Reducing this to one login per bundle does
not make it safe for concurrent phone use. This collector stays disabled and has
**no periodic schedule**; prefer a separately adapted Web-session reader for results.

### Live App/Web comparison and cloud association (2026-10-25)

The same completed owner-number S2 task was queried without task controls, calls,
recording downloads, analysis generation or production writes:

- App login: the existing phone token queried successfully before the new login.
  Immediately afterwards it returned code -10000 / success=false / "token incorrect";
  the new token succeeded. Phone logs also contained -10000. Device connection was
  absent before this phase, so it did not test loss of box authentication.
- The user then restored the enterprise phone login and connected/authenticated box.
  With a valid phone-token query as baseline, a separate normal Web pcLogin left the
  **same** phone token valid immediately and about 131 seconds later. It was not
  rotated. Four device snapshots remained connected/authenticated and idle. This is
  a short coexistence observation, not a long-running, lock-screen or renewal guarantee.
- Web taskPage returned S2; taskDetailPage explicitly returned parent taskId, child
  id and callId. aiRawResult.callActionId equalled that callId and the independently
  known S2 per-call ID. In this sample aiRawResult.tsdId also equalled the per-call
  ID, **not** the child ID; never infer its meaning from its name.
- Web callDetail was requested with that exact child/call pair. It returned no ID
  echoes; the association uses the verified request scope and independent S2 checks,
  not fabricated response IDs. Its three-segment transcript hash matched S2 exactly,
  duration was 28305 ms, and dialogueSummary equalled the 144-character result summary.
  The structured result retained intentLevel "未明确" and raw intentSignal 25.

The queries used Web cookies, not App tokens on Web endpoints. The original wire
encoding of aiRawResult was not retained in the redacted report; the decoded object
and its ID relationships were checked. No real result was passed into this processor.
The Web reader/automatic binding are now locally adapted and fake-tested; no live
processor invocation has been performed. Whether Web result rows retain every redial
or only a child's latest call remains unverified, so that path requires one attempt.

`YunkeAppCallMapper` is separate from the Web-row inspector. It currently accepts only
App result CONNECTED=3, S2's observed raw hangupType=1 and a nonempty finalized
recording/transcript. Other statuses/hangup values and incomplete/conflicting data are
held without settlement or missed-call messages. This is not the complete vendor enum.
Parent TaskEnum.COMPLETE=4 was independently confirmed in the same APK; a parent
completion or pause bit alone is not a per-call outcome and is not a settlement input.

Channels 0/1 become agent/user turns under the same-version static convention. Duration
is stored in whole seconds rounded up, original milliseconds and all end offsets are
preserved in meta. End beyond duration stays end_exceeds_duration. ended_at is derived
from turnOnTime+recordingDuration, with that provenance retained. Cost stays unknown.
A recording link wider than the `recording_url` column (512) holds the result as
`recording_url_too_long` rather than storing a truncated address.
Flags such as isReceive, isAiAnswer, aiCall and aiAsr do not determine participation.

Only exact history.remark supplies the summary. aiAnalysis is a flag. History tags stay
under analysis.yunke_app; no tag code or label is silently normalized into high/medium/low.
In particular S2's raw 7 / "未明确" does not become low intent or trigger a high-intent alert.
Voicemail/AI-screening classification and other hangup paths need further evidence
before enabling follow-ups for live calls.

### Transactions, duplicates and pending aftermath

The binding and call are locked inside one transaction. Outcome, turns, optional first
analysis and their processing hashes commit together. A rollback leaves all pending.
Duplicate terminal content leaves turn IDs and metadata untouched; first late analysis
is added once. Contradictory terminal or later analysis content is held, rather than
overwriting the accepted result. Unknown IDs never create or link a local call.

The binding records settlement/analysis readiness and separate handled stamps.
`retryAftermath($bindingId)` runs after commit under a shared cache lock, calls the
existing `AiCallAftermath`, then stamps the relevant effect. If the process stops after
settlement, a replay or explicit retry can drain that pending work. Exceptions visible
to this wrapper leave it pending and produce a redacted warning (binding ID and the
exception class, never a message that could carry lead text). Disabling aftermath
preserves the pending stamps for a later explicitly authorized run. Settlement also returns
pending when an explicit customer refusal could not be persisted, even without analysis;
recording that opt-out must precede any later customer follow-up.

Handled means the existing aftermath method returned with nothing still owed, not external
message delivery. The Discussion comment and its `lead_comment_id` / `lead_comment_at`
receipt commit atomically under the call lock. A process interrupted before commit loses
both writes; re-entry after commit sees the receipt and cannot create a second comment.

Thanks is dispatched before `thanks_dispatch_confirmed_at` and the compatibility
`thanks_queued_at` are saved. A crash or failed receipt write after queue acceptance may
produce another delivery to the queue on retry. The `SendAiCallFollowUp` thanks middleware
serializes those deliveries by call; the next delivery re-reads `followup_sent` after the
first has finished. An overlapping duplicate is discarded while the original owns the
lock; the existing worker retry policy is unchanged. This is at-least-once queue
dispatch, not an atomic WhatsApp-send/database-commit guarantee. A failure after the
external send but before `followup_sent` remains subject to the existing delivery limitation.

Legacy `lead_comment_at` without `lead_comment_id`, or `thanks_queued_at` without dispatch
confirmation or `followup_sent`, is ambiguous. Those effects remain pending for review,
without blindly posting/queueing again or stamping `analysis_handled_at`. No automatic
legacy cleanup or production backfill is installed. A post-call replay must not guess a
comment association from text, time or phone.

Ordinary comment/queue failures return false so only owed work is retried. High-intent
alerts retain the existing `hot_lead_alert_at` claim/release behavior: no destination or
Notifier failure keeps them owed. Journey events and tester flags retain their own
idempotency. Other fail-soft aftermath methods remain governed by their logs and jobs.
No new automatic worker or notification subscription is installed here.

Retell's webhook, reconcile and budget queries now select only Retell rows. Yunke pending rows
are never queried through Retell, prematurely timed out by its sweep, or charged against
its estimated budget. Retell placement/profile settings and hashes are unchanged.

## Reference usage

The runnable consumer is
`YunkeAppResultIngestTest::test_duplicate_result_settles_once_and_runs_real_followup_logic_once`.
It builds a single-call claim, parses a fake task response, explicitly binds IDs, collects
five fake HTTP responses, writes a test call/transcript and invokes real aftermath with
`Queue::fake()`. It asserts one lead comment and one queued follow-up after a replay.

Other regressions cover default-off behavior, unknown creates, conflicting bindings,
wrong identity, authentication failure, unsupported status, late summary, transactional
rollback, cache-lock contention, pending-effect recovery and Retell isolation. The S2
fixture replaces all IDs, URL, speech and epoch and is not an original wire response.
No live task, customer message or production record was used by these tests.

## Related files

- `database/migrations/2026_10_25_090000_create_yunke_app_call_bindings_table.php` — ledger schema; deployment migration has not been run.
- `src/VoiceAgent/YunkeAppCallBinding.php` — states, scoped keys and local call relation.
- `src/VoiceAgent/Repositories/YunkeAppCallBindingRepository.php` — transactional claims, IDs and processing stamps.
- `src/VoiceAgent/Support/YunkeAppCallMapper.php` — supported App result normalization.
- `src/VoiceAgent/Services/YunkeAppResultIngest.php` — explicit collection, ingestion and pending-effect drain.
- `src/VoiceAgent/Repositories/AiVoiceCallRepository.php`, `src/VoiceAgent/Services/AiCallAftermath.php` — shared transactional comment receipt and follow-up logic.
- `src/Common/VoiceAgent/YunkeApp/YunkeAppReadClient.php` — single-auth bounded result bundle.
- `app/Http/Controllers/Webhooks/RetellWebhookController.php`, `app/Console/Commands/ReconcileAiVoiceCalls.php`, `app/Actions/PlaceAiVoiceCall.php`, `src/VoiceAgent/AiVoiceCall.php` — provider isolation and label.
- `config/services.php`, `.env.example`, `phpunit.xml` — default-off controls and test overrides.
- `tests/Feature/VoiceAgent/YunkeAppResultIngestTest.php`, `tests/Feature/VoiceAgent/YunkeAppReadTest.php`, `tests/Feature/VoiceAgent/RetellWebhookTest.php`, `tests/Fixtures/VoiceAgent/yunke-app-s2-redacted.json` — fake-only verification and provider collision regression.
