# Yunke Web — session reads and automatic explicit binding

Part of the [AI Voice Agent](/docs/modules_handbook/shared/voice-agent/readMe.md).
Built 2026-10-25 from the separately verified S2 cloud relationship. Tests use a
synthetic subset with replaced IDs, speech, summary, URL and epoch; it is not a wire capture.

## What it does

`YunkeAppResultIngest::collectWeb()` reads one already accepted single-recipient task
using an existing Web Cookie. It derives the explicit child/call pair, validates the
detail and atomically binds and processes that result through the existing Yunke ledger.
It shares the App processor's duplicate protection, first late analysis support and
separately gated aftermath. No real result was ingested in this implementation task.

All gates default off. Collection requires both `YUNKE_APP_RESULTS_ENABLED` (the existing
shared processor gate, despite its legacy name) and `YUNKE_WEB_READ_ENABLED`.
`YUNKE_APP_AFTERMATH_ENABLED` independently controls the shared follow-up drain.
The Web Cookie and exact company/user scope are configured through
`YUNKE_WEB_READ_COOKIE`, `YUNKE_WEB_READ_COMPANY_CODE` and `YUNKE_WEB_READ_USER_ID`.
No runtime environment or production migration was changed or executed here.

This reader installs no login, refresh, task sender, caller or public endpoint.
A separate default-off [bounded watch](/docs/modules_handbook/shared/voice-agent/yunke-watch.md)
now schedules only accepted local bindings and pending effects through this collector.
The reader fetches metadata/transcripts only. Applied/duplicate results may enqueue the
separately default-off [private recording copy](/docs/modules_handbook/shared/voice-agent/yunke-recordings.md)
after commit; queue/failure state is independent of result settlement and messaging.
App login can invalidate the phone session, so this
Web path never falls back to App authentication. Cookie expiry is a visible error;
session provisioning and long-running renewal remain separate, unimplemented work.

## How it works

### Bounded Web reads

`YunkeWebReadClient` permits only these HTTPS POST queries on `crm3.yunkecn.com`:

| Method | Path below `/phone-ai-call/web/aiCallOut/` | Body |
| --- | --- | --- |
| `listTasks()` | `taskPage` | page, pageSize, companyCode, userId |
| `listTaskResults()` | `taskDetailPage` | taskId, pageNum, pageSize |
| `getCallDetail()` | `callDetail` | subTaskId, callId |

Requests use the configured Cookie, company and userId headers plus source=yunkepc
and channel=4. TLS verification is on; redirects, refresh, retry and automatic
pagination are absent. Pagination size is bounded to 30. HTTP authentication failures,
redirects, business codes -10000/20002, other business errors and malformed responses
throw safe `YunkeWebReadException` reasons. They never become an empty result.
Explicit owner/ID contradictions also throw. Inspector strips headers and payloads
for this host, including Cookie, transcript and summary; exceptions retain no vendor message.

### Explicit association and held results

The consumer requires an existing CREATED ledger entry with an accepted literal taskId.
The ledger already enforces one local UUID, one recipient and one task per attempt.
It compares configured company/user before HTTP, then requests results page 1 / size 30:

1. Require total=1 and exactly one returned row. Empty, partial or multi-row pages stay held.
2. Require that row's explicit taskId, companyCode and userId match the ledger.
3. Interpret `row.id` as subTaskId and `row.callId` as callActionId. Present aliases must agree.
   Require `callNum=1`, `phoneCallCount=1`, integer `callStatus=3` and integer
   `hangupType=1` or `2`. S2 verified 1; the separately approved 21:58 owner task
   verified 2 with native/Web explicit IDs, 156723 ms, 19 original turns and matching
   analysis. No broader vendor hangup enum or inference about who hung up is implied.
   Missing/multiple attempts, numeric strings and other outcomes stay held. A separate
   [offline missed/busy contract](/docs/modules_handbook/shared/voice-agent/yunke-unconnected.md)
   supports status 2 only with a verified reason dictionary; that dictionary is empty by
   default and no real missed/busy codes have been enabled.
4. Never change an existing child/call binding to a different attempt. Fetch callDetail
   using the exact pair for a connected result. The separate verified missed-only contract
   uses its explicit page result without a recording query. Authentication/read errors
   propagate before any new binding.
5. Validate the complete transcript/analysis, then `bindAndApply()` commits IDs, outcome,
   turns, optional analysis and readiness stamps in one database transaction. Any held
   result or write failure rolls back new IDs too. An action already bound to another
   local call stays held. Unexpected storage errors propagate.

Held means no call is settled or guessed and no new partial association is persisted;
the caller receives a safe reason. There is no additional quarantine table or automatic
retry worker. Phones, timestamps, names and notes never select a record. Unknown create
responses cannot be promoted by result scanning. Each redial requires its own attempt;
whether the Web API retains every attempt or only a child's latest call is still unverified.

### Transcript, structured analysis and provenance

`YunkeWebCallMapper` is separate from the App row mapper. S2 callDetail had **no ID
echoes**: missing echoes remain absent, while any present echoes must agree. The
persisted meta records which detail ID fields actually existed. No response ID is fabricated.

The detail duration must equal the row's positive callDuration. Channel 0/1 becomes
agent/user using the shared S2 transcript grammar. Original millisecond spans and the
observed `end_exceeds_duration` issue are preserved; seconds round up. End time is
derived from turnOnTime+callDuration and labeled as derived. Recording URL is metadata, and
one wider than the `recording_url` column (`AiVoiceCall::RECORDING_URL_MAX_LENGTH`, 512)
holds the result as `recording_url_too_long` instead of letting non-strict MySQL truncate it;
cost remains unknown. `meta.yunke_app` is the existing ledger's metadata namespace;
`result_transport=web` and `sub_task_id` identify this path explicitly.

The native ends are text-duration estimates, not measured audio-word boundaries.
Existing static evidence reproduces all 19 ends of the two-way owner sample exactly.
The known overrun now has a management-page warning; see
[timing provenance](/docs/modules_handbook/shared/voice-agent/yunke-transcript-timing.md).
Text return remains verified with that qualification; precise alignment is not an
additional PDF API requirement and no original span is rewritten.

Only aiRawResult with the exact callActionId can supply structured summary/intent.
If dialogueSummary is nonempty, it must equal that summary. Missing/empty structured
summary leaves analysis pending; the first later summary can be applied once without
replacing turns. A contradictory later accepted result stays held.
Summary provenance is `web.taskDetailPage.aiRawResult` under `analysis.yunke_web`.
Raw intentLevel, intentSignal, confidence and tsdId are retained selectively. S2's tsdId
was the per-call ID, **not** the child ID, and is never used for association. Raw
"未明确" is not normalized to high/medium/low. Transcript/analysis JSON string forms
and decoded object/list forms are tested; original S2 wire encoding was not retained.

The owner-call recovery independently verified native `intentLevel=中意向`, integer
tipType=9 in both row and detail, and detail tipName=中意向. The 21:58 two-way owner
sample additionally verified `intentLevel=高意向`, integer tipType=1 in both sources
and detail tipName=高意向, with a matching summary and explicit callActionId.
Only those complete matching combinations write standard `medium` or `high` after
outcome/transcript validation. Raw facts remain alongside
`intent_mapping=verified_medium_label_and_tags` or `verified_high_label_and_tags`.
Missing/conflicting echoes, numeric strings, unknown labels and unverified low
combinations remain unnormalized. No intent is
inferred from confidence, intentSignal, summary text or aiAnalysis; the recovered
call's aiAnalysis stayed 0 despite persisted summary/intent.

The new hangup/high-label regression failed against the old mapper (`held` instead
of `applied`). With the narrow correction, **19 Web ingestion tests / 462 assertions**
pass using synthetic responses and network access restricted to local testing MySQL.
Replay preserves turn IDs and settlement time; unknown integer 3/string `2` outcomes
stay held. The real owner task's original monitor remained on the frozen old mapper
and stopped within twenty minutes after holding that result. Any subsequent same-call
processing must be recorded separately; this fix does not create or dial another task.
Neither message delivery nor private audio copying is enabled by the correction.

A further synthetic verified-high contract enables aftermath only in testing memory:
repeated `collectWeb()` calls produce one Discussion comment, one mocked `ai_call.hot_lead`
notice and one queued thanks follow-up. This connects native high normalization to the
shared business path without a real send. Web ingestion/high-alert checks pass 26 tests /
481 assertions; presentation checks add 9/174 and six component tests. These are offline
contracts, not delivery receipts or proof of webinar classification quality.

The same existing two-way owner result was subsequently collected with the corrected
real Web reader/processor: four live queries, `applied` then `duplicate`, 19 stored turns
(10 agent/9 user), matching summary and normalized high intent. Turn IDs and settlement
time stayed unchanged. This occurred after the original bounded phone monitor closed;
it was not another task/dial or an uninterrupted corrected-version trial. Original end
spans include `end_exceeds_duration` and were preserved. See the dated
[owner acceptance record](/docs/modules_handbook/shared/voice-agent/yunke-owner-acceptance.md).

The real recovered sample still has empty recordingContent and missing outcome fields,
so it stays held. A synthetic complete S2 contract combined with the verified medium
facts checks normalization, one fake follow-up/comment and replay; it is not presented
as a complete real sample. Targeted verification passes **45 tests / 583 assertions**
across Web/App ingestion, high-intent alerts and pilot reports. Recovery-shaped negative
cases neither settle nor dispatch follow-ups/copies, even with their memory-only gates
on. One existing XML deprecation remains; outbound traffic was denied except the local
test database. No live query/write, phone operation or runtime gate change occurred.

After commit the existing `retryAftermath()` and its independent gate handle ready
effects. Existing App [transaction and retry limits](/docs/modules_handbook/shared/voice-agent/yunke-app-results.md)
still apply; handled stamps are not an exactly-once external-delivery guarantee.

## Reference usage

`YunkeWebResultIngestTest::test_web_auto_binding_settles_once_and_reuses_the_existing_aftermath`
constructs a local single-call ledger, supplies a **fake** accepted creation response,
then invokes `collectWeb($bindingId, app(YunkeWebReadClient::class))`. Only result-list
and call-detail HTTP requests are faked; real shared writers and aftermath run against
the testing database with Queue/Notification faked. Replay leaves three turn IDs unchanged,
one lead comment and one queued follow-up. No task-creation request is sent.

Other tests cover both disabled gates, unconfirmed parents, scope errors, ambiguous pages,
multiple attempts, auth failure on either read, conflicting/reused IDs, late analysis,
rollback on database failure and log redaction. The existing App, Retell webhook and
simulated-call regression files remain part of the relevant verification.

## Related files

- `src/Common/VoiceAgent/YunkeWeb/YunkeWebReadClient.php`, `YunkeWebReadException.php` — bounded Cookie queries and safe failures.
- `src/VoiceAgent/Support/YunkeWebCallMapper.php` — Web ID and result normalization.
- `src/VoiceAgent/Support/YunkeCallTranscript.php`, `YunkeAppCallMapper.php` — shared transcript grammar and existing App mapping.
- `src/VoiceAgent/Services/YunkeAppResultIngest.php` — explicit Web collection and shared pending effects.
- `src/VoiceAgent/Repositories/YunkeAppCallBindingRepository.php` — atomic bind and apply; existing schema is reused.
- `config/services.php`, `.env.example`, `phpunit.xml` — disabled defaults and isolated test overrides.
- `app/Support/Monitoring/RedactingInspectorTransport.php` — Web host redaction.
- `tests/Feature/VoiceAgent/YunkeWebReadTest.php`, `YunkeWebResultIngestTest.php`, `tests/Fixtures/VoiceAgent/yunke-web-s2-redacted.json` — synthetic HTTP/ledger verification.
- `tests/Unit/AgentApp/FcmInspectorRedactionTest.php` — actual Inspector transport redaction regression.
