# Auto Oncall Core Classification, Execution, and Publication Contract

### Read-only diagnostic deadline observation

The manual analysis API accepts `noDiagnosticTimeout?: boolean`, default false.
Only `mode=read` may set it true; write-mode opt-in is rejected at the request
boundary. A request-local policy makes the runner's overall diagnostic budget,
scenario/Agent stages and Agent9 model-turn stream wait log
`diagnostic_would_timeout` at their ordinary thresholds instead of aborting.
Logs are operational observations, not Agent input, answer content or completion
judgments. Timers are cleared on stage/request completion, and caller cancellation
is retained. No environment/global switch changes automatic oncall behavior.
Provider single-operation deadlines, authentication and ordinary network/upload
timeouts are unchanged. The classifier and post-analysis Judge are outside this
policy. Isolated replay Job and collector retain the one-hour hard limit.

> Status: Active design and operating contract

This document is required reading before changing Auto Oncall scenario
classification, handling mode, provider routing, missing-context behavior,
diagnostic execution state, final answer completion, risk handling, or
customer-visible publication.

The paired customer/internal response lifecycle after the Router decision is
owned by `DUAL_MESSAGE_CONTRACT.md`; changes to Final Response, persistence,
delivery, replay, evaluation, or optimizer consumption must read both
contracts.

The purpose of this contract is to give every fact one owner. A later stage may
derive a decision from an earlier field, but it must not add a parallel field
that restates the same fact and can disagree with it.

## 1. Stage boundaries

```text
Jira ticket
  -> Jira Context Gate
  -> Scenario Classifier
  -> Auto Coverage Gate
  -> Scenario Router assignment
  -> persistent Scenario Diagnostic Agent
       -> Evidence Agent plan
       -> deterministic Provider Executor
       -> Scenario Diagnostic Agent local decision or one new evidence question
  -> Scenario Router reconciliation
  -> Final Response Agent wording
  -> final-answer safety
  -> Customer Reply Gate and publication validator
  -> Jira internal or customer-visible comment
```

The stages have different responsibilities:

0. The runner materializes the complete JSM request-comment timeline before
   semantic classification. A successful read admits the Jira Context Gate. An
   HTTP 404 carrying the exact Jira Service Management i18n key
   `sd.customerview.error.vpOriginMissing` proves only that the current issue is
   not available through the required JSM request context; it produces the
   business skip `jira_request_context_unsupported` before any classifier or
   analysis Agent starts. Project key, issue type, request channel, and an empty
   Request Type field are observations, not Gate inputs. Other 4xx, 5xx,
   network, and unknown failures remain execution failures with their existing
   retry semantics.

1. The Scenario Classifier describes the problem and selects how it should be
   handled. It does not report whether a later Provider execution succeeded.
2. Auto Coverage decides whether the selected scenario and handling mode are
   enabled. It does not reinterpret the classification.
3. Scenario Router assignment fixes the canonical entity set, provider region
   when the selected Provider requires one, incident window, provider, bounded
   scenarios, the evidence source for each scenario, and the reason each
   scenario was selected. A materialized execution plan or performance trace
   is a candidate input, not a completion or Provider-prohibition decision.
   The Router selects `supplied` only when that artifact can answer the exact
   scenario objective; it selects `provider` when the question still requires
   cluster-side state, workload attribution, replica synchronization,
   scheduling, or another fact the artifact cannot establish. The
   Scenario Diagnostic Agent treats that reason as the hypothesis from which it
   derives the initial evidence question; the reason is never passed directly
   to the Evidence Agent as a provider query objective.
   Runner-owned task-boundary facts from Scenario Classification are supplied
   directly to the Scenario Diagnostic Agent. They must not depend on the
   Scenario Router repeating the classifier's exact signal text in
   `signalRefs`.

For a historical replay, the runner supplies the immutable replay cutoff, its
explicit timezone offset, and a bounded fallback discovery envelope. The
Scenario Router owns interpreting an incident date, clock time, or interval
that is already present in the frozen ticket. A clock-only time uses the
cutoff's local calendar and UTC offset, choosing the latest occurrence no later
than the cutoff; it must not silently become UTC or be replaced by the later
human-reply time. When the ticket says the current value rose or changed from
the same clock interval yesterday, yesterday is the comparison baseline and
the primary incident remains on the cutoff-local calendar date. The Router must
not replace the current incident anchor with that earlier baseline. The runner
canonicalizes the Router's finite absolute range,
rejects a range after the cutoff or longer than 30 days, and uses the fallback
only when the ticket has no explicit incident time.
When a ticket explicitly asks what caused CPU or another resource value to
increase starting at one stated time, the Router's canonical diagnostic range
includes a bounded pre-increase comparison segment as well as the incident
segment. For a clock-only onset, use the fifteen minutes immediately before
the onset plus the fifteen minutes starting at it. This authorizes the later
Scenario phase comparison without allowing the Scenario Diagnostic Agent or
Evidence Agent to widen the fixed range. A lower point after the reported onset
is not the pre-increase baseline.
For `workload-hotspot`, the Router fixes only the exact incident window; it does
not anticipate or authorize a historical baseline by widening that window.
After consuming incident-local evidence, the Scenario Diagnostic Agent alone
decides whether distinguishing an event-local excursion from an unusual
absolute level is load-bearing. It expresses that need through the typed
`prior_7_daily_same_clock` refinement policy. The runner then derives seven
prior equal-duration same-clock windows without changing the canonical incident
anchor.
4. One persistent Scenario Diagnostic Agent per scenario owns the initial
   evidence question, consumes each materialized handoff, and either completes
   the local diagnosis or asks one new load-bearing question.
5. Evidence Agent and Provider Executor acquire facts for that exact question:
   the Agent chooses a neutral plan and result fields; deterministic code
   validates, executes, and materializes the outcome.
6. Scenario Router reconciliation owns the one ticket-level diagnosis,
   deduplication, conflict resolution, evidence precedence, mitigation,
   severity, remaining requested context, human-handoff decision, and any
   official product-documentation link selected to support the canonical
   answer. It also preserves every explicit customer diagnostic subanswer that
   a Scenario Diagnostic Agent has already resolved at bounded strength. For a
   plan-choice question, that means keeping separate the evidence-supported
   reason the optimizer selected the observed plan, the actual work that made
   this execution slow, and whether a comparable alternative is proven better;
   an unavailable exact cost comparison is a stated boundary, not permission
   to omit the bounded selection explanation. It may search current official
   PingCAP documentation for that product-knowledge task. It does not query a
   diagnostic Provider, reopen Provider output, or use documentation to replace
   incident evidence.
7. Final Response owns wording and organization only. It cannot change the
   Router's diagnosis or typed decision fields.
8. Customer publication uses the final answer and actual execution outcome. It
   must not infer execution success from classification intent.

Repository-owned product facts have one separate source under
`product-knowledge/`; they do not belong to response-format instructions.
The line-oriented `index.ndjson` contains one compact searchable topic record
per line and points to one topic file. Primary Analysis searches the index with
concrete ticket terms and, when the typed ticket has a non-empty `orgId`, one
exact-literal `orgId` lookup for customer-scoped context. It inspects at most
eight matching rows across those searches and reads only the applicable topic
files; it never loads the whole knowledge corpus. An `orgId` knowledge match
does not change the typed Cloud-versus-OP boundary or select a Provider. For a
third-party integration question, Primary Analysis prefers an initial
official-site query containing the canonical entity pair, but treats `site:` as
a source-priority hint rather than an exclusivity gate. It always follows that
round with at least one unrestricted canonical entity-pair query, even when the
official-site results appear sufficient, and may run additional bounded rounds
by varying integration-form terms when needed to discover materially distinct
paths. It verifies the applicable paths with official sources. For the
diagnostic path, the runner performs only bounded keyword recall from that
index. The Scenario Router receives at most eight candidates and alone selects
zero to three semantically applicable topic references; the runner then
supplies those exact topics to the same Router for reconciliation. When exactly
one selected topic is explicitly tagged for `alert-firing-explanation`, the
runner also supplies only that topic to that Scenario Diagnostic Agent so it
can define and interpret a rule-equivalent evidence question. The Scenario does
not select the topic, receive unrelated topics, or treat rule knowledge as
incident evidence. Deterministic keyword recall does not decide applicability,
create a Scenario, or replace a diagnostic Scenario. The Final Response Agent receives only the Router's
canonical decision and never receives the index or topic references, so it
cannot add, reinterpret, or correct product facts.

For the exact TiFlash MPP dispatch error `Failed to register MPP Task ... task
is already registered`, repository product knowledge owns the known mechanism:
a coordinator retry after an RPC timeout or transient network problem can
dispatch the same task twice; TiFlash accepts the first dispatch, reports the
duplicate registration on the second, and current TiDB handling can abort the
query. The Scenario Router explains that known mechanism and the public tracking
Issue when the exact topic is applicable, while keeping the current incident's
actual timeout or network trigger unconfirmed without aligned evidence. Generic
resource metrics cannot replace this exact mechanism, and the knowledge does
not establish a shipped fix or release timeline.

For a planned TiFlash restart, repository product knowledge owns the versioned
query-impact boundary. TiFlash graceful shutdown starts in v8.5.4: it rejects
new MPP tasks and waits a configured bounded duration for running tasks. A
v7.5.6 TiFlash restart does not drain running MPP tasks, so affected in-flight
SQL can fail. Multiple replicas preserve availability but do not move an
already-running task off the terminating instance. The semantic answer owner
must answer this impact and avoidance question before reopening root-cause
discovery: a low-traffic, one-host-at-a-time restart reduces but cannot
eliminate the failure window, and production execution remains human-owned.
`INFORMATION_SCHEMA.TIFLASH_REPLICA.AVAILABLE` is a Boolean table-replica
availability indicator, not a count of available instances; do not read
`REPLICA_COUNT=2, AVAILABLE=1` as one of two replicas being available.

Live initial analysis and explicit continuation use the same analysis
dispatcher. A `direct_answer` classification normally selects Primary
Analysis; an eligible read-only Provider route selects the Scenario Router
pipeline. A materialized direct-artifact candidate does not overwrite the
classification. For a diagnostic scenario it selects the Scenario Router even
when the classifier considered the artifact potentially direct, so the Router
can choose `supplied` or `provider` against the ticket's exact objective.
`inputMode=continuation` is context and lifecycle metadata, not a reason to
select a legacy analysis path or let Primary Analysis query a Provider
directly.

Primary Analysis is the sole semantic answer owner for its selected
non-diagnostic direct path. It owns applicability of supplied facts,
repository product knowledge, official documentation, bounded risk, missing
customer context, and the direct-path canonical response pair. Diagnostic
artifact applicability belongs to the Scenario Router and its selected
Scenario Diagnostic Agent path. Primary Analysis does not
become a diagnostic Provider entry point: it must not query Clinic, Wetech, or
Manus, start an Evidence Agent or Scenario Diagnostic Agent, or synthesize a
Provider-backed incident diagnosis. Those cases remain owned by the Scenario
Router pipeline.

Response-format policy is not an analysis source. It owns language,
organization, length, Jira-safe Markdown, and audience projection only. It may
state how to express a responsibility decision already made by Primary
Analysis or the Scenario Router: omit requests for Support-queryable data from
the customer message, state the customer-relevant open conclusion and Support
follow-up, and keep the exact Support action in the internal message. It must
not determine whether evidence is customer-owned or Support-owned, whether a
Provider capability exists, or change diagnosis, causal strength, mitigation,
severity, `human_required`, requested context, or production approval.

Persisted Codex threads are role-scoped as `primary_analysis` or
`scenario_router`. Continuation resumes a thread only when its recorded role
matches the current dispatch decision. A missing, historical untyped, or
different-role thread is not resumed as another Agent; the selected role starts
from the canonical Jira timeline through the trigger comment. Local Codex
history has a rolling 30-day retention boundary. Once its session file has
expired, a persisted business-store thread id is treated as missing rather than
sent to Codex for resume. A diagnostic run
persists the Scenario Router thread, never an Evidence Agent, Scenario
Diagnostic Agent, Final Response Agent, or publication thread.

Runner-owned Jira context materialization occurs before diagnostic reasoning.
When the bounded ticket text contains an exact customer support-ticket key,
the runner may resolve that key directly only after the current and referenced
tickets share a Jira Service Management organization. It supplies the Router
with cutoff-bounded status, link events, and comment timelines. Exact customer
references do not compete with same-reporter fuzzy recall and do not require a
new diagnostic Scenario. The runner owns reference extraction, organization
authorization, cutoff filtering, and retrieval status; the Scenario Router
alone owns whether the related history establishes shared investigation,
recovery, intervention, remaining uncertainty, and the response action.
Related-ticket text is reconciliation context, not a direct signal for selecting
a diagnostic Scenario for the current ticket. Deterministic route normalization
must consume only the current ticket, visible comments, customer evidence, and
normalized diagnostic summaries.
Same-reporter fuzzy recall is limited to tickets active within the 90 days
before the run cutoff. Same reporter is not sufficient: admission additionally
requires an exact stable error signature, the same concrete product component,
or the same specific symptom family. Generic environment, customer, deployment,
or product words do not establish similarity. Customer-supplied exact ticket
references remain governed by the same-organization boundary instead of this
fuzzy-recall gate.
For the diagnostic multi-turn path, the runner must copy the materialized
`related-evidence.json` into `DiagnosticFrozenContext` supplied to both Router
phases. A prompt that merely tells an Agent to read a workspace file is not a
handoff because the Scenario Router is tool-free and may not read that file.

## 2. Scenario classification fields

`ScenarioClassification` contains the following fields:

| Field | Sole owner and meaning |
| --- | --- |
| `scenarioClass` | What kind of support problem this is. It does not determine completion or publication by itself. |
| `resolutionMode` | How Auto Oncall should handle the case before execution. It owns answer handling, not Provider success or availability. |
| `evidenceProvider` | The selected executable evidence route for new classifications: `clinic`, `wetech`, `manus`, or `none`. It is the sole owner of whether the runner has a Provider route, independently of final human ownership. It does not report success. Historical persisted `investibook` values remain readable but must not be emitted by a new classifier or routing decision. |
| `lookupKeysPresent` | Canonical routing or lookup keys already present in the ticket context. |
| `missingKeys` | Critical inputs demonstrably absent at classification time whose absence prevents safe handling or prevents the selected Provider from starting the current bounded task. It must use the canonical vocabulary below and must not be reused for optional diagnostic refinements, later Provider failures, or final-answer gaps. |
| `riskFlags` | Bounded risk observations used by proportional safety policy. A risk flag is not automatically a publication denial. |
| `signals` | Explainability and policy signals. They are not a second source of truth for the typed fields above. |

There is intentionally no `evidenceRequired` field. Provider selection is
already owned by `evidenceProvider`; answer handling is owned by
`resolutionMode`; whether selected evidence was obtained is owned by execution
state.

`scenarioClass` follows the customer's current requested outcome: the answer,
decision, explanation, validation, diagnosis, or action that Support is
expected to provide now. The classifier first restates that specific question
or task in its reason before choosing the route. The summary or title is one
clue, but an explicit request in the description or visible comments governs
when they differ.
Impact, severity, environment details, observed metrics, suspected causes,
motivation, constraints, future plans, and consequences are supporting context
unless the customer explicitly asks Support to diagnose, explain, investigate,
resolve, or act on them. A symptom or impact remains the entry problem when it
is itself the explicit request. If answering only a contextual symptom or
downstream consequence would leave the explicit customer question unanswered,
that context must not select the scenario or handling mode.

When the explicit request is to review or validate proposed methods, settings,
commands, or configuration, the proposal is the target. Runtime symptoms,
production impact, cluster identifiers, and incident timestamps supplied to
motivate the review remain context and do not imply an incident-diagnosis
request. A Provider is selected only when the stated target requires discovery
of current or historical facts not already supplied. Availability of Provider
lookup keys is not itself a reason to use the Provider. A proposal assessable
from the supplied command, configuration, plan, and product semantics is a
`direct_answer` with no Provider.

The requested outcome's product or workflow domain selects `scenarioClass`;
the way Auto Oncall should handle it selects `resolutionMode`. A self-contained
how-to, configuration, or validation request may therefore be `direct_answer`
without becoming `feature_usage_or_capability`. When the requested subject
belongs to a more specific scenario domain, the classifier uses that domain.
For a method or configuration review, that domain follows the product,
artifact, or workflow being reviewed rather than a downstream resource symptom
mentioned as motivation.
`feature_usage_or_capability` is reserved for product behavior or capability
questions not represented by a more specific scenario class.

A specific SQL, Digest, execution plan, slow-query record, or explicit
query-tuning request is `sql_performance_tuning`. The diagnostic Router selects
`single-query` for that selected target's diagnosis, plan-choice explanation
and bounded optimization advice. Multiple executions, plans, databases or
engine comparisons of that target remain one target-specific question.
An overall service or cluster
Duration/P99/P999 increase with slow queries only as a suspected explanation
remains `cluster_runtime_issue`; Provider workload discovery is downstream
diagnosis and does not retroactively rewrite the entry class.

Environment identity is owned first by the typed Jira project boundary and then
by `orgId`. Exact project keys `APID` and `NAID` mean OP and take precedence
over organization- or cluster-shaped ticket fields. For every other project, a
non-empty typed `orgId` means Cloud and a missing `orgId` means OP. Other
project keys, ticket prose, labels, comments, `clusterId`, `tenantId`, cluster
aliases, and Account Alias do not select the environment. Account Alias selects
a supported account-specific Provider only after the ticket is identified as
OP.

For a Cloud read-only diagnostic, the routing input is complete when the typed
`orgId` is present and either an exact typed `clusterId` or at least one explicit
customer-visible cluster name or alias is present. An exact `clusterId` binds
one target directly. An explicit name or alias is recorded as
`lookupKeysPresent=cluster_alias`; its missing `clusterId` is Support-owned
target resolution, not `missingKeys=cloud_cluster_id` and not customer
clarification. If neither an exact ID nor an explicit target reference exists,
`cloud_cluster_id` remains the canonical missing key.

## 3. Resolution modes and legal combinations

| `resolutionMode` | Meaning | Provider and missing-key contract |
| --- | --- | --- |
| `direct_answer` | The ticket and already supplied material are sufficient to generate an answer without an additional Provider run. | `evidenceProvider=none`; `missingKeys=[]`. Supplied ticket text, logs, errors, plans, or attachments may still be cited. |
| `evidence_assisted` | A bounded read-only Provider run is part of the automatic answer path and the routing inputs needed to start it are present. | `evidenceProvider` must not be `none`; `missingKeys=[]`. |
| `clarification_needed` | One or more concrete customer-owned inputs are missing, so the customer message should ask one focused question. Available read-only evidence may still be acquired when a Provider route can start, except that an explicit SQL optimization request with no customer-selected SQL target stops before Provider investigation. | `missingKeys` must not be empty; `evidenceProvider` may be selected or `none`. If the missing input remains load-bearing after diagnosis and the result asks the customer, the L1 fallback requires final `decision=human_required`. |
| `human_required` | The automatic path must not own the final customer handling, for example a privileged operation, unsupported evidence route, unavailable system-owned metadata, or proportional safety boundary. Bounded read-only diagnosis may still run for support review. | `evidenceProvider` may select that read-only route or be `none`. The human boundary belongs in `missingKeys`, `riskFlags`, and the final decision reason. |
| `skip` | The ticket is outside the target support automation scope. | `evidenceProvider=none`; `missingKeys=[]`. |

The Scenario Classifier Agent owns the semantic choice. Its prompt and
structured output schema supply the legal combinations and missing-key
vocabulary. The parser validates those fields and rejects invalid output; it
does not infer, drop, rename, or otherwise repair the Agent's semantic choices.
In particular, `direct_answer` must not carry a Provider route and
`evidence_assisted` must not exist without one or carry a missing key.

`missingKeys` is a closed vocabulary for new classifier payloads:

```text
cloud_org_id
cloud_cluster_id
cluster_or_tenant_context
cluster_alias
account_alias
manus_target
sql_or_digest
time_window
job_or_task_id
```

Every emitted key must be absent from the complete supplied ticket fields and
visible comments. A plan, trace, screenshot, metric, log, exact window end,
root cause, or other information that would merely improve or narrow a later
diagnosis is not a missing key when the selected Provider can start without it.
SQL or Digest is not missing when either is already supplied. An incident
window is not missing merely because an exact end is absent when the ticket
supplies an incident timestamp or bounded window, or when the Provider can use
a reasonable bounded default and discover the relevant interval.

The classifier input includes `customerEvidence.sqlDigests` from the same
runner-owned extractor used to materialize the workspace customer evidence.
Live and historical comment selectors preserve the original Jira author and
account metadata. Bridge-speaker display normalization happens only when
rendering comments; changing the transport author before classification loses
the bridge identity needed by the customer filter. Workspace evidence and
classifier evidence use the same filter without a replay-only bypass.
This projection retains description/comment provenance and uses only the
caller's visible comments with the existing customer-author filter; it must not
scan excluded or later comments from the ticket. A supplied Digest establishes
SQL identity even without SQL text or a plan. The classifier records that fact
in the existing `lookupKeysPresent=sql_or_digest` field and does not request it
again. An empty Digest projection does not establish that SQL text or a plan
is absent. Semantic classification stays with the classifier; downstream
parsing and admission do not rewrite its missing-key decision.

Provider capability determines whether an absent fact is customer-owned at
classification time. Once Clinic, Wetech, or Manus has the routing target it
needs to start, the exact incident window is a Support-owned discovery input
through bounded default windows. For a symptom-led incident such as slow query
or cluster-query-latency regression, SQL or Digest is also Support-owned because
TopSQL or Slow Query can discover workload candidates. These
inputs must not produce `clarification_needed`.

That workload-discovery rule does not permit the Provider to guess the subject
of a target-specific customer question. When the customer asks about one
specific execution plan, expected access path, hint, join order, or operator
but supplies no SQL, Digest, or concrete plan identifying that target,
`sql_or_digest` remains customer-owned and classification must preserve it.
This is true even though the Provider route can start and collect generic
evidence.

An explicit request to optimize or tune SQL with no target SQL, Digest, or
concrete plan and no concrete slow-query, latency, resource, or other runtime
symptom has the same customer-owned target boundary. It is not a symptom-led
workload-discovery request: classification preserves
`missingKeys=[sql_or_digest]`, and diagnostic admission stops before Scenario
Router assignment, Provider bootstrap, or evidence acquisition. Primary
Analysis asks only which SQL or Digest the customer wants optimized, and its
internal message states that investigation waits for that target. It must not
present globally discovered TopSQL or Slow Query candidates, speculative
indexes, or rewrites before the customer identifies the target.

Exact Wetech and `apac-test` Account Aliases select the Wetech Provider but do
not identify a cluster. Wetech routing requires one explicit customer-supplied
cluster alias, business name, or full cluster name. When none is present,
classification uses `clarification_needed`, preserves `evidenceProvider=wetech`,
and emits `missingKeys=[cluster_alias]` so the customer is asked to confirm the
affected cluster and available identifying information. It must not infer a
regional default from the account, geography, Jira key, or another ticket alone.
The explicit Wetech OP shorthand `亚太01` / `亚太 01` and `亚太02` / `亚太 02`
is covered by `wetech-regional-saas-shorthand` product knowledge: default to
the matching inventory candidate `asia-prod/SaaS01` or `asia-prod/SaaS02`,
continue bounded diagnosis, then ask the customer to confirm that assumed
cluster in the answer. Explicit other business/full names take precedence;
other accounts, bare region, unlisted numbers, conflicting regions, and absent
inventory candidates do not receive this default. Scenario Router owns the
mapping, while classifier admission recognizes the explicit numbered Wetech
shorthand as `lookupKeysPresent=cluster_alias`, not a missing key. The LLM
classifier and deterministic compatibility classifier share that bounded
recognition; coverage normalization removes only a mistaken `cluster_alias`
gap for this supplied shorthand and preserves independent missing inputs and
safety boundaries. It neither chooses SaaS nor changes Gate enabled scenarios
or resolutions. Scenario Router owns the
mapping and final confirmation; use the existing scenario reason and response
fields, not another target-state field. The final question requires
`human_required`, clarification true, and focused customer-owned requested
context even when a separate Support query gap exists. If
an explicit target later fails unique internal resolution, execution and the
Router record that Support-owned gap rather than asking the customer twice. Manus still
requires one explicit `vida` or `monica` target because selecting between those
isolated targets is a genuine scope ambiguity rather than internal discovery.

## 4. Provider routing and evidence execution

A Provider route is selected when:

```text
evidenceProvider != none
```

This is intentionally independent from final answer ownership. For example,
`human_required + evidenceProvider=wetech` may collect bounded read-only facts
for the support engineer while still prohibiting an automatic customer answer.
`direct_answer` and `skip` must not select a Provider.

Provider authentication/bootstrap and query execution are runner-owned. The
Scenario Classifier never claims that evidence was acquired.
For a provider that requires shared authentication/readiness, bootstrap is a
hard prerequisite for the whole evidence pipeline. A failed bootstrap is
recorded once and stops before any Scenario Evidence Request, Evidence Agent,
Provider Executor, Router reconciliation, or Final Response phase starts.
An unresolved Wetech or Clinic target is not a failed bootstrap because no
authentication or Provider request has started. When the Scenario Router
returns no exact authorized target, the runner materializes one bounded
target-resolution packet for each selected scenario, skips bootstrap and every
per-scenario evidence or diagnostic phase, and continues Router reconciliation
and Final Response. The result requires `decision=human_required`, keeps
`requestedContext=[]`, records failed evidence acquisition with the
provider-specific `diagnostic_wetech_target_missing` or
`diagnostic_clinic_target_missing` code, and completes through the normal
internal delivery path without a worker retry or service-error outcome.

New Cloud read-only diagnostics select Clinic directly, including SQL
performance, hotspots, latency, resource, alert, cluster-runtime, and TiCDC
investigations. They do not select Investibook or depend on an
Investibook-to-Clinic fallback. Exact `Wetech` and `apac-test` Account Aliases
select the isolated Wetech OP route, including for TiCDC diagnostics. Exact
`Manus` selects its isolated OP route only for SQL-performance and
cluster-runtime diagnosis; it does not provide an OP TiCDC route. Neither OP
route falls back to the Cloud Clinic route. Wetech and Manus retain independent
configuration switches, but deterministic OP Support admission has one
outcome: an unknown or scenario-unsupported OP Account Alias, a recognized
Wetech route while Wetech is disabled, or a recognized Manus route while Manus
is disabled is normalized to
`resolutionMode=human_required`, `evidenceProvider=none`, and
`riskFlags+=op_unsupported`. A recognized route avoids `op_unsupported` only
while its Provider switch is enabled. New Gate signals must not emit separate
`gate:wetech_op_disabled` or `gate:manus_op_disabled` reasons. Provider access
remains independently fail-closed for historical or externally supplied
workspaces and uses the same `op_unsupported` reason.

This deterministic normalization also applies when an LLM has already returned
`human_required + evidenceProvider=none` for a read-only unsupported OP TiCDC
diagnosis. That output shape must not bypass the OP Gate or retain an
account-specific unsupported risk alias. Privileged operations and independent
product/data safety risks retain their owning human-review boundary instead.

A request to read exact current PD, TiKV, TiDB, or TiDB-variable configuration
values from an identified Cloud cluster is a
`cluster_runtime_issue + evidence_assisted + clinic` request, not an operation
request. A statement that the customer may later request a production
configuration change after reviewing those values describes a possible future
request only. It does not set `requiresPrivilegedAction` and does not skip
Clinic. The Scenario Classifier selects `operation_request + human_required`
only when Support is asked to perform or approve the mutation in the current
request.

TiCDC diagnostic coverage uses the ordinary Auto Coverage scenario and
resolution allowlists. It has no issue-level replay canary and no classification
hard stop for absent Cloud CDC metadata. Cloud TiCDC uses Clinic; the Provider
Executor owns bounded TiCDC metadata execution and sanitization where the
cluster type supports it, and a failed or unsupported metadata operation is a
Provider query outcome rather than a classification `missingKey`. Exact
`Wetech` or `apac-test` OP TiCDC uses Wetech metrics and logs and never requires
Cloud Dataflow changefeed metadata. Other OP TiCDC accounts remain
`human_required + evidenceProvider=none + op_unsupported`.

This opens only internal Auto-oncall scenario processing. It does not add TiCDC
to the customer-publication scenario allowlist, change Clinic public API
authorization, permit a production operation, or make a Provider result
customer-visible. Automatic mode continues to write only the stable
`public=false` Jira internal comment.

For Cloud TiCDC, the Evidence Agent may pair sanitized metadata with a bounded
log query when a runtime marker such as `newarch=true` is load-bearing. An
explicit control-plane field or aligned startup/deployment marker is the
strongest direct architecture proof. When it is absent, the Scenario Diagnostic
Agent may confirm only that the exact changefeed is executing through the
new-architecture runtime path when the same target and window show a coherent
chain across Maintainer, dispatcher, Event Service, and where observable Event
Store or Log Service. It must disclose the absent direct field/marker. Version,
dedicated/shared or deploy type, Dataflow identity, metric-family existence,
and one owner/dispatcher series remain insufficient alone; a classic
compatibility metric is counterevidence rather than an automatic veto of a
complete aligned runtime chain.

New TiCDC routes use four bounded Scenario IDs:

- `ticdc-deployment-topology` owns the exact changefeed/TiCDC target,
  independent TiCDC version/build, dedicated/shared deployment, and
  new/classic kernel architecture question;
- `ticdc-changefeed-control-plane` owns create/update/delete/list/status and
  requested-versus-effective configuration lifecycle;
- `ticdc-replication-progress` owns the ResolvedTS/CheckpointTS branch and the
  architecture-specific upstream scan/puller/Event Service/Event Store/
  dispatcher or downstream sink path;
- `ticdc-replication-correctness` owns missing or inconsistent replication,
  DDL/schema tracker, filter/ineligible-table, rename, syncpoint, and recovery
  safety.

The historical `ticdc-checkpoint-lag` identifier remains readable for replay
compatibility but must not be selected by a new route. TiCDC version, source
TiDB version, deployment topology, Dataflow control-plane identity, and
new/classic kernel architecture are independent facts. No Agent may infer one
from another. Each non-topology TiCDC Scenario obtains the strongest available
provider facts needed to select its architecture-specific evidence branch.
Cloud may use sanitized TiCDC metadata; Wetech OP uses its exact runtime
metrics, logs, and supplied task context without treating absent Cloud metadata
as an evidence gap.

For Clinic, an exact typed `clusterId` becomes the sole candidate without a
discovery request. When only explicit cluster names or aliases are present, the
runner loads at most 100 non-deleted cluster metadata candidates from the exact
typed `orgId`. The sanitized Scenario Router input contains only that org's
cluster ID, name, provider, region, and status. The Router must resolve every
explicitly named ticket target to one unique candidate, return only exact
candidate names, preserve at most three targets, and return no target if any
explicit target is missing or ambiguous. Short aliases may match longer names
only when the ticket geography, product words, and numeric suffix make the
candidate uniquely clear. Deterministic code validates exact same-org candidate
membership and maps the names back to IDs; it does not guess, perform fuzzy
matching, silently omit one named target, or cross an organization boundary.

The runner supplies the resulting exact target set to each selected scenario.
The Evidence Agent writes one neutral plan for that set and cannot discover,
add, remove, or substitute a target. The Clinic Provider Executor applies each
independent plan operation concurrently to every target. A target-specific
failure preserves successful target facts, marks that query and the acquisition
partial, and retains the failed target as an explicit gap. A query is complete
only when it completed for every resolved target.

For Wetech, the runner supplies the Scenario Router with a compact target
candidate list containing only region, canonical alias, business aliases, and
known full cluster names. It does not expose Grafana URLs, Dashboard routes,
datasource UIDs, credentials, or session state. The Router owns the
semantic resolution and returns the candidate's exact canonical alias and
region:

- default to `asia-prod` (Aliyun Asia);
- select `middle-east-prod` only when the customer explicitly identifies the
  Middle East, or an explicit cluster name contains `gcp`;
- an explicit name containing `ali` selects `asia-prod`;
- require a specific customer-supplied candidate alias, business role, or full
  cluster name, or an explicit shorthand covered by applicable product knowledge;
  apply the bounded Wetech Asia SaaS convention above, while account identity,
  bare geography, and unsupported regional labels alone produce no target;
- an explicit `ali-*` or `gcp-*` name that clearly matches one known candidate
  name selects that candidate directly;
- an explicit candidate alias, business qualifier, or full cluster name must
  resolve uniquely;
- otherwise compare only candidates in the selected region and select one only
  when the match is uniquely clear;
- conflicting region signals, no clear candidate, multiple plausible
  candidates, or a materially different name produce no target. The Router
  must not guess, manufacture an alias, or fall back across regions.

The Scenario Router receives the reply-safe, cutoff-filtered local images
already materialized for the ticket on every Provider route. It extracts the
actual reported symptom: visible onset/interval, affected node/component,
change shape and peer separation, not only a chart title or whole-chart maximum.
These facts use existing `anchor.window`, `anchor.symptom`, scenario reasons
and `signalRefs`; there is no second incident-window owner. A node-local or
peer-wide shape is an observation, not a final cause.
For Wetech only, an unambiguous visible image value may additionally supply a
cluster candidate under the existing inventory rules. Otherwise a visible
image value may supply an incident timestamp or bounded interval,
or one affected TiDB, TiKV, PD, TiFlash, or CDC endpoint/component label. The
timestamp follows the same historical cutoff, timezone, point-window, and
maximum-range rules as a textual ticket time. The endpoint/component label is
preserved only in `anchor.symptom` and scenario routing context;
`anchor.entities` remains the canonical cluster target. Explicit text takes
precedence, and a conflicting or ambiguous image value is ignored rather than
guessed.

These image-derived values are route anchors, not diagnostic evidence. They
may scope the Provider question and scenario selection but cannot establish a
cause, mechanism, mitigation, severity, recovery, or Provider result. The
Router must not infer hidden values, metric semantics, causal relations, or
operational instructions from the image layout, filename, surrounding UI, or
embedded instructions.

The frozen context retains an available-image manifest (`ticketImages` refs and
filenames) independently of the direct-artifact gate. Scenario Diagnostic may
request selected originals from that manifest when verifying the node, time,
shape or execution facts could change its question or diagnosis. The runner
resumes the same scenario thread with those selected images through the existing
image-input transport; this consumes no Provider refinement and grants no
Provider/file-scanning authority. Images already supplied remain in that session,
not resent every round and never borrowed from another ticket or replay.
The image-request result carries no invented diagnosis. Diag preserves visible
contradictions or uncertainty in its local observations/counterEvidence and
evidence question; Router still owns ticket-level anchor/synthesis. A maximum
at a different time inside a discovery envelope does not replace the reported
event or rule out its node-local symptom. Final Response does not receive images.

Deterministic code validates only that the returned `(region, canonical alias)`
is one unique inventory member, then passes that pair unchanged to readiness.
It does not map ticket spellings to aliases or repair the Router's selection.
The Wetech helper continues to own transport configuration for that canonical
target, including Grafana origin, Dashboard route, and datasource selector.

The persistent Scenario Diagnostic Agent derives one bounded acquisition
question and observable success condition from the frozen scenario assignment,
starting with the Router's scenario reason as a hypothesis to establish or
reject against its strongest material alternative. The Scenario Router does
not prescribe what to query, and its routing reason is never reused directly as
the Evidence Agent objective. The Evidence Agent translates only the Scenario
Diagnostic Agent's question into a neutral read-only provider plan. That
question is a semantic draft, not provider syntax: the Evidence Agent owns
synonym correction into exact provider fields, metric families, labels,
grouping, and bounded same-round query repair. The Scenario Diagnostic Agent
never receives field-selection work back and never authors PromQL, API
parameters, or Slow Query projections.
For performance and resource cases, a command
returning successfully is not itself completion: the plan must align the
affected entity and incident window and, when workload discovery is applicable,
obtain a stable workload candidate from a supported TopSQL or Slow Query
surface, or materialize the exact limitation that prevented it.
Already-known fallback surfaces belong in the same batch.

For `capacity-resource-pressure`, workload discovery is not applicable merely
because a resource trend increased. Its Evidence Agent uses range metrics to
compare same-entity usage, real quota or effective limit, and aligned queue,
throttle, backlog, or demand signals. It may use Activities when a bounded
configuration, scaling, maintenance, or deployment change could materially
change the capacity conclusion. TopSQL, Slow Query, and Statements belong
only to a separately selected workload-attribution Scenario; the capacity
Scenario must not add those detail surfaces by default. Clinic therefore allows
`metrics_query_range` and Activities across the Router's full maximum 30-day
diagnostic window while keeping TopSQL, Slow Query, exported SQL, and logs at a
24-hour maximum. These limits are ceilings, not default query sizes. The
Evidence Agent starts with the narrowest incident and baseline window that can
answer the question, normally no more than 24 hours, and expands metrics or
Activities only when a multi-day trend or change-history question is
load-bearing. When a ticket explicitly asks for a multi-day capacity trend or
recent change history without giving an exact start, the Router authorizes a
30-day envelope ending at the frozen cutoff or live snapshot; ordinary
no-timestamp incidents retain the one-hour fallback.
Workload-hotspot historical comparison is not a Router envelope exception. The
Evidence Agent starts incident-local and receives historical windows only after
the Scenario Diagnostic Agent determines that absolute abnormality, recurring
high-water behavior, headroom wording, or mitigation is load-bearing. The
runner supplies seven separate prior daily windows; one Provider batch may
transport them together, but each window remains an independent query and
result rather than one multi-day request.

Statements is an optional supplemental workload surface for Clinic and Wetech,
never a stable discovery or attribution surface. The Clinic frozen target does
not establish that the cluster has the AWS-only Statements datasource, while
non-AWS clusters may not configure it. Wetech cluster-group Statements is
low-sampled, so rows cannot establish rank, prevalence, aggregate contribution,
or a representative baseline, and an empty result cannot establish absence.
Evidence Agents may add one narrowly bounded Statements query only after the
same plan or a prior handoff establishes the workload candidate through TopSQL
or Slow Query. Provider Executor owns the `supplemental` role: a successful row
may corroborate that existing candidate, while an empty, unconfigured, or failed
Statements result remains visible in query coverage and the compact artifact but
does not enter repair candidates, scenario completion, evidence-acquisition
degradation, or human handoff. Clinic also skips transport retry for a
supplemental Statements failure. TopSQL remains the aggregate workload surface and
Slow Query remains the exact-execution, plan, and transaction-linkage surface.

Clinic TopSQL uses the explicit `topsql` Evidence-plan operation. Provider
Executor always sends it through the canonical org/cluster-scoped Data Proxy
SQL API over `clinic_data_proxy.topsql`; an Evidence Agent must not represent a
TopSQL objective as `metrics_range`, invent a Prometheus TopSQL family, or rely
on a special query ID. The canonical result is time/partition bounded and uses
typed optional `component`, exact `instance`, SQL-Digest, plan-Digest, and
`rankBy` selectors. For a node-specific question, the Evidence Agent first
selects the exact component and instance and receives a fixed instance Top20 at
SQL granularity. A SQL-Digest may be combined with the same instance to localize
its plans. A component-only query ranks that component across instances, while
omitting both component and instance is the explicit cluster-global discovery
mode. Every unfiltered ranking has a fixed Top20 even when an Agent requests a
larger limit. It ranks non-empty SQL Digests without plan fan-out. CPU time is
always projected; the Evidence Agent may select at most four load-bearing
non-CPU aggregates, including the selected rank field, from execution count,
duration, read/write keys, logical read/write bytes, and network in/out bytes.
Evidence plans name those aggregates with the closed logical selectors
`exec_count`, `avg_latency_ms`, `read_keys`, `write_keys`,
`logical_read_bytes`, `logical_write_bytes`, `network_in_bytes`, and
`network_out_bytes`, never with the underlying Data Proxy column names.
Provider Executor normalizes the corresponding historical physical column
aliases before applying the same closed-set and scan-count validation.
It must not request every exported column by default because each Parquet
column adds scan cost. Plan count remains part of SQL-level ranking. Provider
Executor obtains the selected component or instance CPU total through a
separate CPU-only aggregate without a Digest filter, rather than an analytic
window over ranked rows. Datasource nulls remain unavailable and are never normalized to
zero. The local compatibility helper keeps raw normalized SQL and plan text
internal; the Agent9 Managed Tool omits normalized SQL from broad list rows
under the compact-fact contract below. A separate bounded supplied-SQL
candidate query retains plan detail without consuming ranking slots. When a
deterministically matched supplied SQL is absent from a complete selected-scope
Top20, Provider Executor emits the cutoff CPU and selected-scope share as a
conservative contribution upper bound instead of expanding rank 21 or deeper
rows into the handoff. An optional exact or 6-to-63-character SQL-Digest filter,
and the equivalent plan-Digest selector when a SQL-Digest is present, use prefix
matching below 64 characters. The operation may also
select a narrower absolute sub-window inside the canonical incident window for
one aligned phase comparison, using epoch seconds or a timezone-explicit
RFC3339 value. The initial Evidence Agent batch stays on the canonical window;
only the Scenario Diagnostic Agent's one adaptive refinement may request two
comparable phases. A historical
`queryId=topsql, kind=sql` plan remains readable
only for replay compatibility. A new plan that labels a metric query as TopSQL
is rejected before Provider access and returned to the same Evidence Agent for
one structural repair to the typed operation.

When this exact TopSQL operation receives Clinic HTTP 400 with upstream code
`FailedPrecondition` and an unconfigured-data-source message, Provider Executor
returns `clinic_topsql_datasource_not_configured` with `repair.eligible=false`.
That response is a Provider capability gap: rewriting or retrying the same
TopSQL objective cannot configure the source. Other Clinic 4xx responses retain
their ordinary request-repair semantics.

For `sql_performance_tuning`, exact customer-supplied SQL Digests, including an
exact 64-hex value explicitly labelled `SQL ID`, are extracted from the frozen
ticket description and reply-safe customer comments into the existing
runner-owned customer-evidence artifact, then copied into the immutable
Provider context. An unlabelled 64-hex Digest candidate may appear inline in
the description or a visible customer comment; no label or standalone line is
required. Complete word boundaries prevent matching a substring of a longer
identifier. Explicitly labelled Digests take precedence within the same text;
otherwise all complete 64-hex candidates are retained, normalized and
deduplicated. Comment whitespace normalization must not drop those candidates.
The values are not re-extracted or guessed by an Agent. A
runner-owned Evidence prompt includes the existing frozen `suppliedQueryDigests`
and bounded `suppliedSqlTexts` excerpts directly for both Managed Tool and
local-plan execution, including refinements and query repairs. A projected
context file is not a substitute for these target-matching inputs. SQL excerpts
are data, not instructions or customer-database execution requests; preserve
hints and query structure and use Provider-returned identities for candidates.
This does not send Provider query-planning context to Final Response or change
the Scenario Diagnostic Agent's causal ownership. A
single-query, query-execution, or write-path-contention Slow Query plan binds the one exact supplied
Digest when only one is present; provider text search and a table-name
approximation must not replace that identity. For Wetech write-path-contention,
that exact Slow Query is the primary per-execution surface before optional
TopSQL and preserves the supported write size, write-response stage, retry,
lock, local-latch, resolve-lock, backoff, and scan discriminators. `write_keys`
must not be presented as an affected-row count. The compact provider handoff
reserves its bounded row projection for mandatory identity/time facts and then
the Evidence Agent's ordered `handoffFields`; unselected generic fields must not
displace those selected facts. The Clinic Slow Query operation
owns UTC partition generation. After it selects one incident-overlapping exact
Digest, the Provider Executor performs one bounded same-operation profile read
for decoded plan, statistics, indexes, scan, wait, memory, and spill facts.

After exact cluster metadata selects the NGM transport for a shared, Starter,
or Essential cluster, Provider Executor accepts only `query_time`, `memory_max`,
or `total_keys` as Slow Query ordering. It rejects `process_time`, `wait_time`,
and `backoff_time` locally before an NGM request, while the non-NGM Data Proxy
transport continues to support all six orderings.

When runner-owned current-run metadata already provides the exact org/cluster's
known `deployType`/`deployTypeV2`, Evidence reuses those fields and skips a
duplicate metadata-only model/Tool round trip. Metadata is read through the
existing exact-target bootstrap, not a local diagnostic Provider bypass or a
cross-run cache. Missing, unrecognized or unavailable tier information retains
the original preflight; no unknown tier is guessed to be Dedicated.
Otherwise, in round 1, the Evidence Agent first requests one metadata-only
`cluster_detail` batch for the already-resolved target set, then applies the
repository product knowledge to the returned service tier before planning
other evidence. Runner materialization counts this first metadata-only batch
separately from the at-most-twelve diagnostic query objectives. Its results,
errors, coverage and attempt history remain in the handoff; only its query
count is exempt. A mixed batch, later metadata batch, or refinement-round
metadata call does not receive this exemption. Same-query corrections retain
the existing grouping and attempt limits. For Starter, Essential, and shared targets, both the Evidence
Agent and Scenario Diagnostic Agent apply the knowledge that Clinic does not
expose physical component topology, TopSQL, persisted Statements,
dedicated-cluster configuration, or physical-node
`node_*` Prometheus metrics. The Evidence Agent does not plan those surfaces;
the Scenario Diagnostic Agent does not turn their expected absence into a
refinement, customer request, or human handoff. This is flexible planning
knowledge, not a new capability gate or execution-state schema.

The exact Digest is an Evidence Agent and Provider Executor acquisition input,
not Scenario Diagnostic Agent context. Before the persistent Scenario
Diagnostic Agent receives the frozen ticket context, route reason, or later
route fields, the runner replaces each complete 64-hex Digest with a bounded
prefix. This preserves the fact that exact workload identity was supplied
without giving the diagnostic thread an opaque value that it can repeat into a
causal brief. The Evidence Agent and Provider Executor continue to receive the
unchanged exact value through their runner-owned context, and the scenario
packet parser retains its full-Digest rejection as a final disclosure boundary.

For TiDB non-transactional `BATCH ON <column> LIMIT <N>` DML, product knowledge
owns the split semantics used by the Scenario Router. `LIMIT` guides grouping
of shard-column values and is not a hard affected-row cap: all duplicates of a
boundary value can remain in one generated DML statement. The Router therefore
does not recommend lowering only `LIMIT` when a low-cardinality shard column
can still produce the same oversized transaction. It applies the selected
product topic together with incident evidence, recommends an indexed column
with fewer duplicate values only when applicable, uses `DRY RUN QUERY` and
`DRY RUN` as prechecks, and keeps any causal claim about a specific alert
separate from this product behavior.

Clinic is an observability Provider, not a connection to the customer's TiDB
database. Its Data Proxy SQL endpoint exposes Provider-owned logical
observability tables and validates which logical tables and SQL dialect it
supports; the Managed Tool does not maintain a second table-name allowlist or
reject a read-only statement merely because a logical table is unqualified.
The Tool deterministically qualifies the exact unqualified `statements` table
as `clinic_data_proxy.statements`, because that dataset requires its complete
lowercase name, and does not rewrite unknown tables. It retains single-statement
read-only, length, absolute-window, UTC-partition, timeout, and compact-result
boundaries. The Evidence Agent must still use DDL or schema already supplied in
the frozen ticket as artifact evidence and must not treat Data Proxy as a
customer database connection. If required customer schema is absent, the
diagnostic pipeline preserves that limitation; a Provider rejection remains a
per-query acquisition error with its safe upstream correction detail.
For the Wetech and Clinic Agent9 Managed Tools, default Slow Query discovery
omits detailed plans. Digests retain their full API-returned values.
A request selecting a SQL Digest or prefix includes detailed decoded plans and
compact operator facts for up to three executions, without an Agent includePlan
switch. Wetech Dashboard and Clinic NGM use anchored Digest text filtering for
prefixes before LIMIT, with a returned-row Digest check; their digest parameter
is exact-only. Clinic Data Proxy uses a bounded LIKE prefix predicate.
The Provider Executor requests plan fields only for a Digest-selected query.
Both Providers default broad TopSQL and Slow Query lists to no SQL text.
The optional Boolean `includeSqlText` defaults to false for broad lists and true
for Digest-selected detail. Single-query discovery may explicitly request true
when SQL text is needed for target matching; an overall-latency or hotspot list
uses false and obtains one Digest's text only for a load-bearing detail question.
The Provider result's `sqlTextOmitted` marker describes this deliberate projection,
not credential redaction or an acquisition failure. Digests, numeric facts and
instance/time scope remain unchanged. Keyword or partial-text candidate matching
does not establish exact target identity; the Scenario Diagnostic Agent owns that
judgment.
Wetech uses up to three serial authenticated POST /api/visualplan/generate calls
when incident-overlapping executions expose only binary_plan. Encoded plans stay
inside the Provider; decoded plans accompany their structured operator summaries.
Decode failures preserve the execution's other facts and report the plan gap. Wetech diagnostic logs
separately identify `plan_missing` (no plan field supplied), `plan_parse_failed`
(plan content present but no recognized operators), and `plan_decode_empty`
(encoded input supplied but decoding returned no content). Log query identity,
source fields, format, byte length and decode-attempt metadata only; never copy
SQL or plan contents into these logs. This logging does not change returned
plan statuses or enable fallback to an unparsed plan.
Each plan stays paired with its own Digest, instance, interval and timings. The
runner materializes both Providers' detailed execution rows as individual facts,
avoiding the generic 4,000-character batch cut. Existing fact and handoff budgets
still apply. Root execution time, cop task aggregate time and task maximum/average
time remain distinct; the Provider does not choose a bottleneck from them.
Default lists retain full Digests, instance and key metrics, not SQL text,
while omitting detailed plans. This is evidence selection, not credential
protection. Detailed plans are reserved for a Digest-selected Slow Query. SQL
text remains available when the plan is missing. The local compatibility
executor is unchanged.
That exact structured Slow Query plan is the primary plan source; a screenshot
is supplementary and is not required when the structured plan is available.
The Evidence Agent must not hand-author generic SQL or date predicates for that
profile.

The Provider Executor owns deterministic parameter normalization and bounded
transport recovery. It may retry a transient request or issue one changed
request for a recognized wire-level rejection without consuming a diagnostic
refinement round. When an executed query instead returns a provider semantic
error such as HTTP 4xx, the runner returns that exact failed objective to the
same Evidence Agent thread before scenario diagnosis. The Evidence Agent may
rewrite the query, aggregation, labels, window, step, ordering, projection, or
supported surface while preserving the frozen target and question. It gets at
most four repair attempts per query in the same acquisition round and may stop
earlier when the failed query is non-load-bearing, already answered,
unsupported, or has no bounded repair. It must not retry an unchanged plan.
Only a new load-bearing diagnostic question discovered after materialized
evidence consumes a Scenario Diagnostic Agent refinement round.

Clinic configuration lookup uses the explicit `configuration` operation. The
Evidence Agent supplies between one and sixteen exact `component` and `key`
selector objects for `pd`, `tikv`, `tidb`, or `tidb_variable` in one batch
entry; it does not split exact keys across Tool calls or enumerate
metrics, logs, Activities, or a full configuration payload to discover those
values. The Provider Executor first calls the canonical Clinic Dashboard
configuration endpoint with the exact resolved organization and cluster in
both the path and authorization headers. It never omits `x-org-id` to bypass an
authorization decision. Only keys that Clinic rejects or does not return may
fall back to DevOps CloudConfig. CloudConfig uses an explicit cluster value
when present and the exact cluster-version default otherwise. The compact
result contains only requested non-secret values and their provenance; secret
or credential-like key names, mutation, unrestricted configuration export,
cross-organization lookup, and an Agent-authored CloudConfig request are
prohibited. The fallback and its credential are wholly Provider Executor-owned
inside the same Managed Tool call. Configuration is a current,
time-independent read and therefore carries no incident `start` or `end`.

For single-query on Managed Clinic, independent initial objectives use one
batch after metadata preflight. A focused Digest detail lookup dependent on that
discovery result may use one subsequent batch in the same Evidence Agent Turn,
within the same combined twelve-query budget and exact target/window.
This fulfills the already-known identity/execution question, not a new Scenario
refinement. Other Scenarios retain their existing initial batch contract.

An Agent9 Managed Tool remains an ordinary Provider Executor program at this
boundary. Agent9 supplies the selected package manifest's `parameters` JSON
Schema to the Evidence Agent as the Tool argument schema; the Tool implementation
still owns runtime validation and safe correction details. One Clinic call
carries one bounded batch of at most twelve entries;
each entry carries one stable semantic `queryId`, and the Tool executes the
independent entries with a concurrency limit of six inside the same isolated
Tool Sandbox. The batch returns one compact structured success or error result
per `queryId`; top-level Tool completion never hides a failed entry. Wetech and
Manus retain their existing one-operation call shape. Every Wetech objective
also carries one stable semantic `queryId`; its corrected one-operation call
reuses that ID so materialization replaces the failed outcome while retaining
bounded attempt metadata. Wetech success results preserve that ID for metrics
and every Dashboard operation. If a legacy caller omits or leaves the ID blank,
the helper generates `default-<request hash>` from the canonical arguments
excluding queryId, rather than sharing a constant across unrelated queries.
The Evidence Agent still supplies an objective-specific ID and reuses it for
changed corrections; the helper fallback cannot infer that semantic identity.
A local argument rejection
or any HTTP 4xx includes enough safe correction detail to identify the failed
operation and invalid field or upstream rejection without exposing credentials
or unrestricted provider content. Wetech exposes the Provider's complete
credential-redacted rejection text as `detail_error`; the helper does not
replace label matching, duplicate-series, syntax, or other request semantics
with its own diagnosis or summary. Clinic, Wetech, and Manus use one
model-visible result transport contract for success, failure, and batch
results: `details` is the compact structured result, and `text` is the exact
JSON serialization of that same object. A failure carries its safe Provider or
validation detail as `detail_error`; a success carries its compact evidence
without that field. This is a transport projection, not a second diagnosis or
result representation. For `sql_query`, the canonical call field is
`sql`; the Managed Tool deterministically normalizes the unambiguous legacy
shape where `sql` is absent and `query` is a string, but rejects missing,
non-string, or simultaneous `sql` and `query` inputs as actionable
`invalid_sql`. For both Clinic and Wetech, the Evidence Agent corrects that same
primary objective in its current Turn, reuses the same `queryId`, and may make
at most four changed attempts. A Clinic correction batch contains only failed
primary entries; a Wetech correction is one changed call for only that failed
primary objective. A
supplemental result is preserved per query but is never corrected and never
degrades overall primary acquisition.
Materialization keeps only the final outcome for that `queryId` while retaining
bounded attempt metadata. It folds an unchanged repeated request digest into
that query's ignored-attempt metadata without discarding its first error or any
other query's evidence. A corrected
Managed Tool call is not a new acquisition batch or Scenario refinement round,
and an unchanged retry is prohibited.

Authentication, shared Provider-session bootstrap, readiness, authorization,
and browser/runtime availability are Provider-wide prerequisites rather than
query-parameter failures. When a Managed Tool reports that shared prerequisite
as unavailable before a Provider request, the Evidence Agent preserves the
first failed objective and stops issuing new Provider calls in the current
Turn; results from calls already in flight remain materialized. It does not
attempt argument correction, repeat login, or issue another objective against
the same unavailable Provider session. This terminal same-Turn behavior is
identical for Clinic and Wetech even though Clinic uses one batch call and
Wetech uses one-operation calls.

The Clinic Tool reserves a bounded execution budget below the outer Tool
timeout and divides it fairly by concurrency waves. Every query receives its
wave-sized deadline when it is scheduled, so a slow first wave cannot consume
the deadline of later entries. The fixed concurrency limit remains six; fair
deadlines must not be implemented by increasing Provider concurrency.

Provider Executor ownership is transport-independent. With the local Codex SDK
backend, the Evidence Agent writes the bounded plan and the auto-oncall runner
executes `src/clinic-evidence-batch.ts` as the local compatibility Provider
Executor. With the Agent9 backend, the Evidence Agent calls
only the exact selected Managed Tool; Agent9 AOS validates and executes that
call in an isolated Tool Sandbox, so that Managed Tool operation is the
Provider Executor. Auto-oncall reads the persisted operation's compact
`provider-result-v1`, rejects a cross-provider or malformed result, and
deterministically writes the same canonical compact report and child handoff.
Provider error codes and messages that cross that handoff are also
transport-independent: the materializer preserves the Provider's safe exact
error code when present and otherwise uses a generic Provider Tool or
result-validation code. Agent9-specific operation identity and adapter
diagnostics stay in the runtime trace and must not become Evidence Agent,
Scenario Diagnostic Agent, or Router semantics.
It never treats the Evidence Agent's prose as provider evidence. Manus retains
its runner-level Provider lock. Wetech has no runner-level Turn, target, or
cross-E2B lock: independent Scenario Evidence Agent turns may run concurrently,
and `metrics_query_range` does not wait for Dashboard work or consume a
Dashboard slot. Within one Wetech Evidence Agent Turn, at most two Dashboard
operations (`topsql`, `statements`, and `slow_query`) may be in flight. After
two Dashboard calls, the Evidence Agent observes at least one result before
issuing another. This concurrency control stays inside the same Turn and does
not create another Evidence Agent Turn or Scenario refinement. Clinic does not
share the Manus lock. Agent9 provider authentication happens inside the Tool
Sandbox and is not bootstrapped by the auto-oncall Pod.
Wetech's reviewed package may declare eligibility for unrestricted outbound
internet because its P81 browser handshake does not complete under E2B's
restricted-egress path. Eligibility is not authority: the existing Agent9
Workspace Admin installation boundary must explicitly persist and audit
`networkAccess=unrestricted`. Package publication, the Evidence Agent, Tool
arguments, and invocation policy cannot select it. Organization Auth remains
Org-Admin-owned credential state, while this exact installation network choice
remains Workspace-Admin-owned. Clinic and Manus retain restricted networking.

Those two implementations are distinct runtime owners, not interchangeable
repair targets. A fresh Agent9 replay failure inside Clinic Provider execution
belongs to `tools/agent9-auto-oncall/managed-clinic/`; the local compatibility
helper cannot repair it. A local Codex SDK Provider execution follows the
inverse boundary. Runner-owned materialization and handoff defects remain in
their exact downstream source regardless of backend. The AOS-owned immutable
bundle manifest must pin byte-for-byte SHA-256 identities for every file in the
current Managed Clinic and Wetech source manifests. Repository validation fails
when current source and deployable bundle pins differ, so an image-only release
cannot claim a Managed Tool source change is deployed.

Wetech TopSQL and Slow Query validate their bounded `limit` (integer 1–20)
and Slow Query's optional complete 64-hex `digest` before browser/auth work.
TopSQL's required non-empty exact `instance` string (at most 256 characters,
without surrounding whitespace) uses that same preflight and correction
contract. Omission is not a cluster-wide query; an unavailable exact selector
remains a query gap rather than authorizing guessed instances or a legacy
helper-only selector dependency.
A rejected field returns `dashboard_query_parameter_invalid` with `field`,
`expected`, and the existing `repair.action=correct_request` contract. The
Evidence Agent corrects that same objective in its current Turn using the
runner-owned full Digest; it must not substitute a displayed prefix, widen the
query limit, or send the same invalid request unchanged. These are Provider
argument requirements, not diagnostic decisions or customer missing context.

Agent9 Core Tools and Provider Tools have separate ownership. File reads and
writes, directory inspection, shell execution, local code, and `curl` are
ordinary Agent9 Runtime operations in the current Session Drive; their
availability, filesystem scope, network access, authorization, and audit are
owned by Agent9 and its Codex/AOS sandboxes. Auto-oncall does not maintain a
second allowlist of those operation names and does not reject an otherwise
valid Provider result because the same Turn used them. The Provider
materializer selects only calls to the known Clinic, Wetech, and Manus Managed
Tools, rejects a call to a different Managed Provider than the frozen route,
and ignores other Runtime operations. Ordinary Runtime output never becomes
Provider evidence, and direct Provider access through shell or `curl` cannot
replace the required selected Managed Tool result.

The Agent9 adapter projects the working directory selected by the owning Codex
thread; it does not create an additional per-operation file or command policy.
For an Evidence Agent, runner-owned immutable files that are intended to be
read are placed under that scenario's `context/` directory and projected into
the current Session Drive. Parent ticket workspaces, sibling scenarios, other
runs, repositories, and host paths are not part of that thread's working
directory. Role instructions and the Codex runtime own what the Agent reads or
executes inside the projected directory; Agent9 owns the sandbox boundary.

Agent9 Skill installation follows the same stage boundary. Evidence Agent has
`evidence-query-planning` plus the Provider query Skills `clinic-api`,
`wetech-op-grafana`, and `manus-op-grafana`, and never has a diagnosis Skill. Scenario Diagnostic Agent
has only `op-diagnosis`, `tidb-latency-diagnosis`, and `tidb-query-tuning`; it
may read an applicable Skill's `SKILL.md` and directly referenced files from
its isolated diagnosis directory, but has no Provider Skill or Managed Tool.
Such Skill reads are diagnostic instruction reads, not evidence acquisition or
Provider execution. Scenario Router and Final Response Agent have neither
diagnostic or shared query-planning Skill set.

A reply-safe binary attachment is projected as a selected read-only Agent9
user file while `input/attachment-manifest.json` remains the inclusion and
provenance owner. For a supplied-evidence scenario, the Evidence Agent matches
that file by the exact manifest filename, lists and extracts a relevant ZIP in
fresh sandbox scratch space, and reads only the load-bearing content. It never
executes archive content. A successful upload, checksum, filename, or byte size
is not evidence that the archive was read; a match, list, extraction, or read
failure stays an explicit evidence gap. The runner starts each Evidence Agent
in a scenario-scoped acquisition directory containing the frozen input and
attachment, validates and persists its compact handoff, then starts a fresh
Scenario Diagnostic Agent in a separate directory without the raw attachment.
The Scenario Diagnostic Agent receives those neutral facts only through the
compact Evidence Agent handoff and does not re-read or reinterpret the raw
archive.

The Evidence Agent handoff uses a strict Codex structured-output schema: every
declared object property is required, while semantically optional fields are
represented as nullable and normalized by the backend parser. The parser keeps
read compatibility for historical handoffs that omitted those fields. A schema
rejected before the first evidence operation is an acquisition failure; it must
not be reported as an unread or empty archive.

A successful provider query with no matching rows is complete transport
acquisition, not partial execution, but empty is not one uniform diagnostic
fact. For every metric plan the Evidence Agent declares exactly one expectation:
`expected_non_empty` for a provider-documented common baseline that should exist
for the exact target/component and window, `sparse_allowed` for a legitimately
sparse event/condition metric whose exact selector contract is trusted, or
`unknown` otherwise. Historical plans without the declaration are read as
`unknown`.

The Provider Executor materializes that single declaration into query coverage:
`unexplained_empty`, `verified_empty`, or `unclassified_empty`. A nonexistent or
rejected metric family remains `failed`; neither the declaration nor an empty
repair may convert it to empty. `unexplained_empty` triggers at most one changed
query in the same Evidence acquisition round: the same Evidence Agent keeps the
metric family and performs one minimal bounded selector/label validation or
rewrite. A second empty remains an explicit unexplained gap. `verified_empty`
requires the runner-owned target/window plus a provider-skill-established exact
metric and selector contract; it may support only the narrow observation that
no matching sparse event was returned. `unclassified_empty` and
`unexplained_empty` are never counter-evidence. Scenario Diagnostic Agent sees
the materialized classification and decides only whether that gap is
load-bearing; it never chooses provider syntax. All three empty classes remain
complete acquisition, while `partial` is reserved for failed or otherwise
incomplete acquisition.

Provider field capability is not owned by the orchestration runtime. When an
Evidence plan needs a provider-specific closed field vocabulary, the selected
provider skill points to one small exhaustive reference that the Evidence Agent
reads on demand. That reference also groups the vocabulary by diagnostic
scenario so the Evidence Agent can translate a semantic phase or mechanism
request into exact supported fields and repair an unsupported optional
projection without sending provider syntax back to the Scenario Diagnostic
Agent. The Provider Executor uses that same provider contract. An
unsupported optional field is omitted and reported as a query gap while the
remaining valid plan continues; it must not fail the whole scenario or require
the runtime to maintain a parallel field allowlist.

Wetech Evidence Agent explicitly passes `limit: 5` for ordinary TopSQL ranking
and first queries on a selected instance; larger coverage alone is not a reason
to start at 10 or 20. Wetech TopSQL defaults to five entries; an explicit bounded limit remains available
when the evidence objective requires more. Slow Query defaults are unchanged.

Wetech Dashboard query failures preserve the actual HTTP response status when received. A timeout or network failure before response headers has `httpStatus=null`, never synthetic HTTP 0 or 504. `errorClass` distinguishes these failures; `requestDurationMs` records the request duration separately from total Managed Tool execution. A response-body failure retains an already received HTTP status. Successful Dashboard query results also retain HTTP status and request duration. These are transport diagnostics, not diagnosis or retry decisions.

The Provider Executor also owns compact-fact preservation. A single query fact
may use up to 65,536 JavaScript string-length units, and one Scenario handoff
may use up to 256 KiB of UTF-8 JSON across the
initial batch and at most one authorized adaptive refinement. It preserves all allowlisted categorical and numeric
fields that fit, including workload identity, instance, timing, and peak-memory
fields. TopSQL keeps the five highest-priority rows plus its compact global-rank
and contribution-bound facts; it never carries tail rows merely to name an
exact rank below TopN. Slow Query and other
ranked result surfaces keep ten. The Evidence Agent orders queries from most to
least load-bearing, so budget pressure removes whole later observations first
and reports the omitted query IDs while retaining query coverage and canonical
compact-report references. Wetech and Clinic Managed Tool TopSQL and Slow Query
list facts omit SQL text by default; explicit target-matching and Digest detail
may preserve it with its metrics. If a list exceeds the per-fact
budget, the runner removes whole trailing rows and marks the projected list
truncated with its returned row count; it does not cut JSON or rewrite SQL
whitespace. Provider-side SQL truncation remains a source limitation. Detailed
plans follow the Digest-selected execution rule above.
This selection belongs to the Provider Executor. The runner's evidence-handoff
and scenario decision parsers enforce structure, evidence provenance and size,
without keyword-based secret guessing or SQL/Digest rejection. They preserve SQL
text, comments, plan predicates and complete Digests as diagnostic data, including
SQL fragments cited in a conclusion. Diagnostic prompt serialization does not
rewrite text with a blanket Digest regular expression; Provider output preserves
the complete returned Digest for exact follow-up queries. Agent9's actual injected-secret
output boundary retains credential protection; diagnostic parsers do not duplicate
it with string patterns.
Provider credential protection does not redact SQL, PromQL, plans, Digests,
instance addresses or resource specifications. It redacts injected secrets,
passwords, tokens, cookies, authorization values and private keys on both
success and error output. Existing customer-facing cost/specification and
commercial publication constraints remain separate. Read-only execution,
exact-target authorization and bounded evidence selection remain unchanged.
Metric results include the actual executed PromQL so a query's descriptive
name cannot substitute for its selector and returned labels during review.

Before applying the total handoff byte budget, the runner retains SQL text
once per Provider target, database, Query Digest and SQL field. Repeated rows
refer to that Digest; their timestamps, timings, counts and plans stay intact.
Historical short prefixes coalesce only identical SQL text, not distinct SQLs
sharing a prefix. First occurrences precede dependent rows so trailing-fact
budget removal does not remove a retained row's SQL definition. This is text
deduplication, not execution or plan equivalence judgment, and does not authorize
merging different executions or database scopes.

For every non-empty range-metric series, the Provider Executor preserves the
temporal `p50`, `p95`, `p99`, maximum, and timestamp of the first maximum in
addition to the existing minimum, mean, last value, and sample count. These are
percentiles over time samples within that exact series, not percentiles across
nodes. The stable per-entity reference remains attached so the Scenario
Diagnostic Agent can compare upper-tail separation with the same series'
central tendency and align other metrics around the peak without reopening raw
Provider output.

Clinic log identity is Provider-skill knowledge owned by the Evidence Agent.
A decimal ticket value labelled as a connection, processlist, session, thread,
or SQL ID stays an opaque exact literal and is not promoted to a SQL Digest. A
complete SQL Digest is exactly 64 hexadecimal characters; a 6-to-63-character
prefix is reusable only when a prior compact Provider handoff identifies it as
a Digest prefix. Every Clinic log plan selects `detailLevel=summary|events`.
Summary mode retains bounded counts and time/stream facts. Event mode is used
only when lifecycle order, transition, duration, or exact event kind is
load-bearing. The Provider Executor then emits bounded allowlisted event kinds,
counts, timestamps, safe source locations, booleans, and numeric execution
fields, plus up to twenty matching credential-redacted log lines. SQL, full
Digests, connection IDs, addresses and ordinary URLs are internal diagnostic
data, not secrets. These remain neutral
facts in the Evidence handoff; the Scenario Diagnostic Agent alone interprets
their diagnostic meaning and passes its local causal brief to the Router.
For a Clinic or exact Wetech decoded plan, the Provider Executor may
additionally materialize only a bounded structured operator summary: operator type and depth,
`estRows`/`actRows`, task/store category, execution time, memory/disk bytes,
safe access-object identifiers, plan-Digest reference, statistics flags, and
index identifiers. Selected single-SQL decoded plans retain their raw content
and Wetech execution rows retain the SQL text as described above; broad
list queries continue to omit that detail. For
`sql_performance_tuning`, the Agent9 Scenario Diagnostic Agent reads its
installed `tidb-query-tuning` workflow and applicable bounded plan/MVCC
references. The local Codex SDK compatibility path receives the same bounded
guidance inline. The Evidence Agent remains forbidden from installing, loading,
or applying that diagnosis Skill.
Metric plans must bound result cardinality before execution by aggregating away
irrelevant labels or using a load-bearing top-k. The Wetech Provider Executor
rejects an oversized Prometheus response before JSON decoding so one broad
high-cardinality query cannot exhaust the shared diagnostic process; that exact
gap may motivate a changed refinement.
Shared metric planning is owned by
[`evidence-query-planning`](../skills/evidence-query-planning/SKILL.md).
Both Agent9 Managed Tool and local-plan Evidence Agent prompts require the
shared Skill and exactly the selected Provider Skill before the first query;
the same thread retains both across corrections and refinements. Publication
creates or resolves the exact workspace-scoped shared Skill by name, publishes
an immutable version, and pins it only to Evidence Agent. Local images install
the same repository source. Installing this Skill grants no Provider Tool.

Scenario Diagnostic also retains its own session and diagnosis Skills across
materialized rounds of one scenario/replay, reading new applicable references
only as needed. Its initial request includes a Diag-authored `problemSummary`
(overall customer problem with entity/event/target), distinct from `question`
(this round's acquisition purpose) and `stopCondition`. A refinement may update
that summary with clarified supplied facts; otherwise the initial summary is
retained. Evidence receives both fields and may select neutral, relevant facts
and concise Slow Query summaries; this does not transfer identity or causality
decisions to Evidence. Managed execution returns optional grouped
`slowQuerySummaries: [{queryIds, statement}]` in its acknowledgement. The runner
maps only actual nonempty same-round Slow Query IDs to canonical refs and
replaces covered full-list observations. Unselected observations, original
compact reports, coverage, errors and gaps remain unchanged. Invalid references
discard that summary, not the acquisition. One summary may cite up to the
twelve-query batch limit; diagnosis and completion remain Diag-owned.

The shared query-planning Skill's scope is source-sample work versus returned-series cardinality, authorized
absolute query windows, proven selector provenance, and bounded changed queries
after resource failures. It owns the mandatory exact-endpoint filter and
at-most-15-minute range for `tidb_tikvclient_request_seconds_{bucket,sum,count}`
on Clinic, Wetech, and Manus. With no proven endpoint or documented Provider
mapping, the Agent chooses an available lower-cardinality signal or preserves
the gap; it never uses unfiltered top-k to discover endpoints from this family.
Other families remain LLM-planned; this is not an all-metrics node-filter rule.

Provider Skills retain APIs, schemas, authentication, datasource selection,
operation limits, product availability, exact label vocabularies, and declared
cross-surface mappings. The runner retains frozen context, correction budgets,
and stage transitions. Diagnosis, severity, mitigation, and response wording
are excluded. This extraction does not change empty-result classification,
SQL/Digest handling, or login recovery; those are not part of this Skill.

Mandatory Skill guidance is not an executable validation guarantee. The
existing `clinic_tikv_request_scope_invalid` hard preflight belongs to the local
Clinic compatibility executor, including its existing stricter sub-window
check. Agent9 Managed Tools do not gain that preflight through Skill
installation. This change preserves existing executor checks and moves shared
LLM planning knowledge; a new hard guard must be implemented and tested at the
actual executor in a separate bounded change.

For store-local write-path flow-control diagnosis, Clinic's provider contract
owns one explicit cross-surface chain: a focused, exact-TiDB-instance
`tidb_tikvclient_request_seconds_bucket` result carries the numeric `store`;
`pd_scheduler_store_status{type="store_capacity"}` maps that store through its
`store` and `address` labels. The Provider Executor accepts only a numeric store
paired with a TiKV DNS address on port `20160`, strips the port and DNS suffix,
and emits the exact first-label `tikvInstance`; the source metric's `instance`
and `pod` labels are the PD scheduler scraper and are not TiKV identity. That
also applies to the exact `max by (store, address)` form of the same selector:
Prometheus removes `__name__` and the filtered `type` label from those result
series, so the Provider Executor binds normalization to the exact bounded query
expression. A different aggregate expression or a row carrying a conflicting
metric identity does not authorize the mapping. The derived pair is a
provider-declared deterministic dependency, so the same
Evidence Agent may use `tikvInstance` as an exact selector on
`tikv_scheduler_throttle_duration_seconds_bucket`; it may not generalize this
exception to another metric or derive a selector itself. The chain may also
run in the reverse observable direction: a bounded throttle-duration top-k
supplies one exact TiKV
instance, the next batch obtains bounded store-capacity mappings without
filtering `address` by the short instance name and correlates the exact emitted
mapping to numeric store, and the final focused batch tests Commit/Prewrite on
that exact store. Optional throttle-action or
transaction throttle counters corroborate only when present and their absence
is not counter-evidence to a non-empty throttle-duration histogram. The same
Evidence Agent thread owns both changed refinements; generic per-instance
metric batteries and customer-schema queries do not substitute for the chain.
The shared Skill owns the general source-cardinality and selector-provenance
rules. Provider-declared deterministic mappings such as the Clinic store chain
above and Wetech TopSQL `instanceFromQueryId` remain Provider-specific exceptions.
Here, native aggregation means labels exposed by the metric family already
selected; it never means switching to a Kubernetes pod or container metric.
For an ordinary TiKV CPU question, the Evidence Agent starts with per-instance
`rate(process_cpu_seconds_total[2m])` and compares it with
`tikv_server_cpu_cores_quota`. Pod/container CPU usage, request, limit, and
cgroup throttle families are selected only when the supplied evidence question
explicitly requires a Kubernetes quota, throttle, or cgroup capacity boundary
and the selected provider has independently established that family's label
scope. The Evidence Agent never derives a pod selector from a TiKV instance or
the reverse.
Neutral plan statements retain complete Digests. A Digest is diagnostic
identity, not a credential; its presence must not discard valid observations.

A Clinic `slow_query.digest` is a bare hexadecimal SQL Digest. A 64-character
value uses exact matching; a 6-to-63-character value uses bounded prefix
matching. Values shorter than six characters and non-hex values are invalid.
Provider Executor retains all matching Slow Query rows and uses the selected
row's full Digest for its decoded-plan profile. Compact handoffs retain the
complete lowercase value without a label or wrapper. Historical
`sha256:<16hex>` opaque references remain readable for replay compatibility.
The full Digest remains available to the Evidence and Scenario Diagnostic Agents.

For each OP Slow Query request, the Evidence Agent may order at most twelve
safe `handoffFields` according to the current diagnostic question. Workload
identity, digest prefix, instance, finish time, derived execution interval and
overlap, and query time are mandatory and do not consume that selection. The
selected fields must distinguish a mechanism or its strongest alternative,
for example `stats` for statistics freshness, Cop max/address pairs for TiKV
localization, memory/spill values, resource-control delay, scan/MVCC counters,
lock/backoff facts, or optimizer-phase timing. The Provider Executor validates
the provider-owned contract, adds supported selected fields to the provider
projection, gives them first priority in each compact row, and records omitted
unsupported names. Selected Managed Tool single-SQL detail follows the
SQL and plan exception above.

Clinic Slow Query uses a Provider-owned fixed safe projection rather than the
OP `handoffFields` vocabulary. That projection includes instance and plan-Digest
prefix plus the paired TiKV localization facts `cop_proc_max` / `cop_proc_addr`
and `cop_wait_max` / `cop_wait_addr`, in addition to the existing latency,
scan, wait, memory, spill, and decoded-plan facts. Provider Executor preserves
the plan association per execution when the same SQL Digest has multiple plans;
it must not merge one profile plan into every row sharing that SQL Digest.
The compact handoff orders the identity, plan-Digest, and paired Coprocessor
localization summaries for all retained executions before decoded-plan operator
details, so one large representative plan cannot truncate later executions'
load-bearing TiKV addresses.

Metric evidence must retain its producing semantic statement: source quantity,
unit, labels and aggregation, range function and window, plus any rate,
increase, percentile, inversion, normalization, or display transformation.
Scenario diagnosis compares values only after translating them to the same
semantic quantity. Different recording rules, aggregations, windows, or
explicit transformations are expected to differ and are not a contradiction.
`metric_semantics_unverified` is valid only when like-for-like claims remain
incompatible after normalization or a value violates its own definition or
physical domain. Auxiliary selectors that do not enter causal reasoning do not
create a ticket-level semantics boundary.

Agent-to-agent diagnostic prose must not use small character limits that force
an incomplete sentence. Initial evidence questions, refinement questions, stop
conditions, Router internal context, and Final Response wording therefore have
no separate semantic character cap. Prompts still require concise output. True
structural and transport boundaries remain: safe IDs and artifact paths, the
65,536-unit single compact fact, the 256 KiB Scenario handoff, bounded provider batch
cardinality, and the configured Jira publication byte limit. When those
boundaries omit data, they preserve query coverage, canonical artifact
references, and an explicit omission marker instead of silently truncating a
diagnostic conclusion.

`execution.evidenceAcquisition` owns the actual result:

| Field | Meaning |
| --- | --- |
| `status` | `complete`, `degraded`, or `failed` for the actual Provider execution. |
| `provider` | The Provider route that was actually evaluated. |
| `providerCapabilityVerified` | Whether the selected Provider completed the required bounded capability. `null` when no Provider run was selected. |
| `failureCodes` | Deduplicated final execution or capability failures after same-query correction and supplemental-evidence exclusion. This field owns final acquisition status and runtime-candidate triggering; it is not an attempt history. |
| `providerQueryAttempts` | Optional runner-owned, chronological safe details for every materialized Managed Provider query attempt, including corrected failures, supplemental attempts, and their final outcomes. This full trace is investigation input only; it never changes final acquisition status, candidate deduplication, diagnosis, publication, or monitoring denominators. |
| `providerQueryEvents` | Optional runner-owned observability facts for each materialized Clinic/Wetech/Manus logical query. `complete` and `empty` are transport-successful; `failed` is unsuccessful. These facts do not alter diagnosis or publication decisions. |
| `providerHttpAttempts` | Optional Clinic-only transport facts for each HTTP response attempt, including retries and exact status code. They are observability input, not a second execution-status owner. |

The attempt ledger preserves non-empty Provider query IDs without reapplying
query-plan slug validation. When a result omits its ID, use the call arguments
if present, then `operation:<Operation ID>` (or a per-scenario call ordinal when
legacy traces also lack an Operation ID). These fallback references identify
observed executions, not a recovered semantic query identity, and must not
merge unrelated calls. A successful zero-series or zero-row response is
`empty`, never a failed request; database query outcomes count it as succeeded.

There is no execution-level `required` boolean. Route selection is already
expressed by `evidenceProvider`, and execution records only what actually
happened.

When the v2 diagnostic summary deterministically records
`eligibility.eligible=false` and leaves route, authentication, and all Scenario
execution at `not_run`, no Provider run was selected. Execution therefore keeps
the classified future Provider route but records `status=complete`,
`providerCapabilityVerified=null`, and no failure code. An eligible Provider
route that starts routing but produces no Scenario evidence remains
`degraded`; an intentional pre-route skip must not be converted into a runtime
Provider failure.

The runner separately owns operational completion of the diagnostic model
stages in `trace/diagnostic-multiturn-summary.json`. A Scenario Router
reconciliation timeout and a Final Response timeout remain runner facts. They
must not be injected into any Scenario Router, Evidence Agent, Scenario
Diagnostic Agent, Final Response Agent, diagnosis, requested context, or
response message. For a live Auto-oncall job, the runner may derive a bounded
`runnerNotices` projection from that summary for the existing Feishu completion
notification and as an operational candidate signal for the independent single-ticket optimizer. This projection does not change the job result,
decision, execution evidence state, Jira response pair, publication gate,
evaluation, or answer fingerprint. The candidate signal starts a fresh investigation; it is not a diagnosis,
Provider fact, customer message, or direct alert, and cannot by itself admit a repair.

For Agent9 multi-turn diagnostics, this execution state is derived from the
selected Managed Provider Tool results in each routed Scenario's Evidence Agent
turns. Ordinary Agent9 Runtime operations are ignored, and a later Scenario
Diagnostic Agent `bounded_failure` does not turn successfully acquired Provider
facts into failed acquisition. Final acquisition status deduplicates the same
`queryId` across the complete ordered round and query-repair artifact sequence,
while `providerQueryAttempts` retains every safe intermediate and final attempt
for the Single-ticket Optimizer. A corrected intermediate error or a failed
supplemental query therefore remains inspectable without becoming a current
Provider degradation signal.

Provider output is evidence, not a final diagnosis. The diagnostic agents,
Scenario Router reconciliation, and Final Response Agent retain their ownership
boundaries from `AGENTS.md`.

Before reconciliation, each Scenario Diagnostic Agent reduces its evidence to
one compact local causal brief: status, at most four load-bearing observations,
at most three counter-observations, one leading mechanism and exact open link,
one strongest alternative, workload attribution, mitigation/handoff, and
severity. The Router consumes those local diagnoses. It may resolve overlap,
duplicates, conflicts, precedence, and cross-scenario dependency chains, but it
must not reopen provider evidence or independently redo a scenario diagnosis
from a longer evidence dump. Missing a deeper trigger, unique workload, or
exact peak timestamp lowers causal strength; it does not erase a supported
immediate mechanism or by itself require human handling.

When the customer asks an explicit diagnostic question already answered in a
local causal brief, reconciliation must carry that bounded answer into the
canonical response pair. In particular, an execution-plan answer distinguishes
the optimizer's evidence-supported choice from the execution's actual slow
work and from proof of a better alternative. The Router states unavailable
exact cost or controlled-comparison evidence as a limit without dropping the
supported plan-selection explanation.

Causal strength belongs to each explanation's own positive support. Ruling out,
weakening, or failing to observe checked candidates lowers only those
candidates; it does not promote an unobserved residual explanation. The
Scenario Diagnostic Agent may call a local mechanism leading only when its own
positive evidence is aligned to the affected entity and incident time and
distinguishes that mechanism from the material alternatives. The Scenario
Router applies the same boundary during ticket-level reconciliation: without a
positively supported local brief or observed cross-scenario dependency, a
remaining explanation is only a viable unverified direction, not the most
likely cause. Positive aligned mechanism evidence may still support a bounded
leading conclusion while a weaker material alternative remains viable; the
system does not require every alternative to be ruled out.

An explicit question about why one uniquely identified alert fired selects
`alert-firing-explanation` as its primary Scenario. That Scenario is limited to
the selected rule's source quantity, aggregation, entity scope, configured
threshold and duration, firing interval, and a like-for-like reconstruction.
It does not diagnose why the resource rose, attribute a workload, recommend a
capacity action, or evaluate scale-out. Those questions remain separate
mechanism Scenarios and are selected only from an additional explicit question
or independent positive signal. A generic alert word, an ordinary resource
symptom, or multiple still-plausible alert rules does not select the alert
Scenario. The Scenario's local brief remains input to the Scenario Router,
which still owns the final ticket-level monitoring semantics and response.

Query diagnostics have three separate objectives. `single-query` owns the
customer-selected SQL/request's identity, execution latency, plan choice and
optimization advice. Its Scenario Diagnostic Agent loads `tidb-query-tuning`
regardless of the broader ticket class; overall `cluster-query-latency` and
`workload-hotspot` do not load that target-tuning Skill merely because the ticket
is classified as SQL performance.
`cluster-query-latency` owns overall/multi-query latency distributions and representative
execution/wait phases. A mentioned SQL that is only a suspected cause does not
convert an overall incident into single-query. Select both query Scenarios only
for two independent questions.
The Scenario Router owns that scope choice. `sql_performance_tuning` is a
broader classifier category, not proof of a selected statement. Route
normalization must not use it to replace `cluster-query-latency` with
`single-query` or manufacture a target-specific Scenario.
An overall runtime/P99/P999 increase selects `cluster-query-latency` plus an independent
`workload-hotspot` alternative. A single-query question alone does not
automatically add hotspot; that requires an independent positive resource signal
or explicit resource-attribution question. Hotspot owns CPU, RU, QPS, scan and
TopSQL contribution, not SQL tuning. Broad lists in both overall branches omit
SQL text and plans; missing text alone is not a refinement reason. A precise
load-bearing candidate detail question may obtain that Digest's text/plan.
A resource-hotspot report without latency selects only `workload-hotspot`.
Historical `query-execution` remains readable, not a new route.
The runner may start independent scenario pipelines together.
Agent9 Wetech Evidence Agent turns do not wait on an auto-oncall runner lock.
Metric calls remain independent and do not consume Dashboard slots, while each
Turn keeps at most two Dashboard calls in flight; a Dashboard query that derives
its instance or window from an earlier metric also waits for that metric. The
local Codex SDK compatibility helper retains the same Dashboard concurrency of
two and its bounded metric execution limit. Manus operations remain serialized.
Absence of a Slow
Query digest from TopSQL top-N is a hotspot evidence limitation, not negative
evidence against the latency scenario's request identity.

The Scenario Diagnostic Agent chooses causal evidence for the specific question,
not a universal transaction checklist. It may confirm a bounded CPU workload
cause (`status=confirmed`, `workloadAttribution.status=causal_confirmed`) when
same-component, same-instance, incident-aligned TopSQL CPU contribution explains
the hotspot and an aligned process-CPU change or recovery corroborates it.
Lower-level operator, storage, and transaction-shape details are auxiliary to
that CPU attribution, not prerequisites or automatic refinement reasons. This
does not prove an unobserved internal mechanism, latency causality, or that a
partial contribution explains the whole CPU increase. Rank, global share, or
co-window presence alone remains insufficient; material residuals and
conflicting evidence remain diagnostic questions. Attributing COMMIT or
transaction latency to a particular DML requires linked transaction identity,
the relevant transaction shape, and a direct latency mechanism. General SQL
latency can instead use aligned execution, scan, operator, or wait evidence
without establishing transaction shape.
This admission belongs to Scenario Diagnostic, not Evidence or Final Response.

For named SQL targets, the Scenario Diagnostic Agent establishes target
relevance before ranking mechanisms. An unmatched lock/retry, scan, or
maintenance sample is background evidence, even when its duration is severe;
it does not become the leading alternative or the first refinement merely
because the sample is conspicuous. If no target-relevant alternative has
evidence, `strongestAlternative` may explicitly state that boundary and the
missing target evidence; it must not select an unmatched sample just to fill
the field or use that sample to recommend target mitigation. Target-matched executions and shared
scope-aligned demand/resource evidence take priority. A directly matched
lock-wait mechanism remains admissible and may support bounded mitigation.

A CPU increase can reflect execution volume, workload mix, or CPU cost per
execution rather than one changed SQL. For a demand-source question, the
Scenario Diagnostic Agent prioritizes comparable pre-increase and incident
phases within the authorized range, preserving process CPU, execution rates,
and workload CPU per execution at the same scope. Response latency is not CPU
cost. Peer-wide CPU and query-rate growth may support a bounded shared-demand
conclusion without a uniquely hot node, a single dominant SQL, or a complete
plan audit; it does not prove unchanged plans or equal growth in every SQL.
Absent a real pre-increase phase, preserve that exact limitation and the
remaining application/caller/task origin question. Do not invent a phase,
widen the canonical range, or substitute seven-day history for it.

TopSQL `cpu_ms` is accumulated CPU time in
milliseconds across execution threads; parallel core use is already integrated
and must not be multiplied by core count. Dividing `cpu_ms` by window seconds
and 1000 gives an average-core estimate. A claim about one affected TiDB or TiKV
node requires the exact TopSQL `component` plus `instance` scope. The instance
selector may be the exported `host:port` or the exact Clinic display ordinal
`TiKV-N` / `TiDB-N`; the Provider Executor binds a display ordinal to that one
component node and preserves the actual matched instance in the compact rows. A global
candidate can identify what to localize, but cannot prove node contribution;
the Scenario Diagnostic Agent refines that candidate back to the affected node
before making the node-level causal claim. Full-window TopSQL share owns
resident-workload dominance; it does not close a ticket question about how much
one SQL explains a node CPU increase. For an explicit SQL-to-node-CPU-increase
question, the Scenario Diagnostic Agent keeps phase-delta attribution
load-bearing even when full-window share already proves partial contribution.
After the same-instance process series establishes two non-overlapping
comparable phases inside the canonical diagnostic range, its next adaptive
refinement acquires same-instance process CPU and node-scoped TopSQL
distributions for normalized baseline and hot phases. Those distributions
retain the supplied SQL, leading node-local alternative, and selected-scope CPU
total. The Scenario Diagnostic Agent compares their average-core changes with
the process-CPU change. These ratios are estimates, not exact accounting, and
an unstable process-CPU delta remains an explicit limitation. This direct
attribution comparison precedes a later leader, scheduler, Raft, or storage
refinement; backend alternatives follow only for a material residual or an
unavailable phase comparison. The initial Evidence Agent batch must not
preemptively split TopSQL into opening, middle, or closing phases. Absence from
the complete SQL-level Top20 uses the deterministic cutoff-share upper
bound and does not justify a tail scan or refinement merely to find rank 21.
The baseline phase must precede the reported increase. If the fixed canonical
range begins at or after that onset, the Scenario preserves a
missing-pre-increase-baseline limitation and does not relabel two after-onset
periods as CPU-increase attribution.
Likewise, a full-window per-node mean cannot rule out a short-lived node
hotspot. The Scenario Diagnostic Agent compares each entity's temporal p50,
p95, p99, maximum, and peak timestamp with its peers and aligns other
same-entity signals around that peak. Material upper-tail or maximum separation
is preserved as a localized transient signal even when full-window means are
close. If the compact facts cannot establish the needed peak alignment, the
Agent uses one load-bearing refinement when it could change the diagnosis or
states the exact limitation; it must not replace that question with a global
TopSQL share.
Incident-window p95, p99, maximum, and peer separation describe event-local
shape; they do not establish that the absolute value was unusual for the same
entity. When the explicit question asks about historical abnormality or that distinction
materially changes a supported capacity/headroom action, the Scenario Diagnostic
Agent uses one adaptive refinement
with `comparisonWindowPolicy=prior_7_daily_same_clock`. The runner derives the
seven prior equal-duration windows at the same clock time from the immutable
incident anchor. The Evidence Agent acquires the same resource quantity for the
exact affected entity and peers with identical source semantics, unit,
aggregation, grouping, and useful sampling step through exactly seven separate
range operations. A single Provider batch is only a transport container: it
must preserve seven query entries and seven results and must never replace them
with one multi-day range. A separate ordinary refinement may include one
bounded change-history lookup when that determines comparability. A baseline is comparable only across the same effective
topology, node specification, resource quota, and relevant configuration, or
after an explicitly supplied denominator supports normalization. A proven
change segments the baseline; missing alignment keeps historical abnormality
unknown. A peak near a recurring high-water mark does not erase an event-local
excursion, while an incident-local peak alone does not prove new absolute
abnormality or capacity exhaustion. Neither case supplies a fixed threshold or
an automatic scale-out recommendation.
For a short-lived TiDB node CPU peak without an exact customer-supplied SQL
target, refinement priority follows terminal diagnostic discrimination rather
than an automatic workload-identity chain. Before selecting the next question,
the Scenario Diagnostic Agent checks whether its terminal brief would still
depend on distinguishing the incident-local excursion from the same entity's
recurring absolute high-water range. This historical classification has first
priority only when the customer asks whether the level is unusual relative to
recurring history, or that distinction would materially change a supported
capacity/headroom action. Asking why CPU rose, describing aligned demand
growth, or wanting to use high/abnormal wording is not sufficient. Do not
substitute seven-day history for the immediate demand comparison. When the
historical question is load-bearing, the Agent must not defer it to a later
round that may not fit the Scenario budget.

Only when historical absolute-level classification is not load-bearing does an
unaligned process and query-rate peak, unknown workload concentration, or an
unavailable exact node TopSQL selector make the smallest peer-comparable
same-entity immediate-mechanism set the next priority: connection or session
accumulation, query-processing demand or backlog, and TSO or PD-client wait.
The Evidence Agent translates that provider-neutral question into bounded range
metrics using each metric family's native grouping and the Provider Executor's
stable entity references; it does not copy an `entityRef` into a provider
selector or enumerate guessed `TiDB-0` through `TiDB-N` TopSQL instances.
Missing TopSQL identity limits SQL attribution only. Node-scoped TopSQL phase
comparison is reserved for an explicit SQL-to-node CPU question, or a material
SQL alternative when a provider-valid exact node selector is already
available; it does not precede an observable same-entity runtime, demand,
connection, or control-plane mechanism.

Slow Query `Time`/`timestamp` is the finish-side log print time. Provider
Executors keep the Router's incident window canonical, query a bounded
15-minute finish-time lookahead with at least 100 internal candidates, derive
`start_time=finish_time-query_time`, remove candidates whose execution interval
does not overlap the original incident window, and only then apply the
agent-requested result limit. The raw timestamp must never be called query
onset. Interval overlap establishes temporal correlation only; a same-row
`memory_max` establishes that execution's peak-memory observation, not by
itself process RSS causality or the cluster-level root cause.

## 5. Final answer completion

This section owns the diagnostic semantics and typed completion decision. The
end-to-end production, identity, persistence, replay, delivery, evaluation, and
optimizer rules for the two messages are canonical in
`DUAL_MESSAGE_CONTRACT.md`.

Classification intent is not final-answer completeness. Scenario Router
reconciliation owns the semantic fields below; the Final Response Agent always
produces the two audience-specific Markdown messages from that one canonical
decision and may change only their wording without changing facts or
boundaries:

- `decision` and `decisionReason`: whether the next action requires human
  diagnostic, clarification, operational, safety, or authorization ownership.
  Under the L1 fallback, every customer clarification is human-owned;
- `requestedContext`: unresolved information still needed;
- `clarificationSimulation.required`: whether customer clarification remains;
- `customerReplyMarkdown`: the normalized customer message. It may be a final
  answer, progress update, or one focused clarification question;
- `internalHandoffMarkdown`: the normalized internal message containing the
  evidence boundary, next owner, internal action, and escalation condition.

These audience-explicit names are canonical across Agent schemas, runtime
objects, APIs, replay, evaluation, and optimization. Historical
`commentDraftMarkdown` and `replayContextMarkdown` values may be read at a
compatibility boundary only; new results must not emit them.

The two messages are the only response surfaces. They are not independent
diagnoses and no duplicate semantic fields are added. The Router supplies both
canonical drafts; the Final Response Agent rewrites both in one turn; replay,
evaluation, persistence, and delivery preserve both. Publication eligibility
decides whether the customer message is sent, not whether either message is
generated.

The single-ticket optimizer may promote one already verified `mode=read`
artifact through `POST /v1/tickets/publish-read`. This is deterministic result
handling, not another analysis stage: it preserves the same run ID, paired
messages, fingerprint, execution, and Judge result, and performs only the
authorized stable internal-comment and persistence writes. Missing or
mismatched server-owned artifacts fail; the caller cannot supply replacement
message or diagnosis fields and the service does not fall back to a rerun.

The post-diagnostic ownership matrix is:

| Stage | Owns | Must not do |
| --- | --- | --- |
| Scenario Router reconciliation | Ticket-level diagnosis, evidence precedence, duplicate removal, conflicts, causal strength, alternatives, mitigation, monitoring semantics, capacity action, severity, requested context, human handoff, and the applicability and exact language variant of any supporting official product documentation | Query a diagnostic Provider, reopen Provider output, use documentation as incident evidence, or delegate documentation selection to the wording stage |
| Final Response Agent | Concise wording, organization, one ticket language shared by both messages, Jira-safe Markdown, and audience projection for the canonical pair; `internalHandoffMarkdown` is only the meaningful information omitted from the customer message, never a repeated summary; it translates low-level acquisition state into the affected technical evidence, blocked customer decision, concrete Support action, and human-facing escalation condition without exposing machine fields, error/status identifiers, machine-form target references, or orchestration lifecycle; for a resolved Wetech Provider run it preserves the Support-readable region and cluster name supplied by the Router; the customer message preserves only the resulting open conclusion and Support next action; an `internal_only` result with no additional internal information gets the language-appropriate no-additional-information marker | Remove a semantic fact or documentation link from the canonical pair, repeat customer content in the internal message, transcribe runner or Provider state into the Support note, select a different replay draft, emit non-material audit narration, truncate a load-bearing conclusion for an arbitrary character count, or change diagnosis, mitigation, ownership, severity, requested context, clarification behavior, or decision |
| Deterministic result handling | Parse the typed result, preserve the selected replay draft, enforce size/schema integrity, and persist the artifact | Search for documentation, map locale paths, rewrite prose, or reinterpret semantic fields |
| Customer safety and publication | Deny disclosure, cross-tenant content, destructive or privileged promises, unauthorized commercial/policy commitments, or ineligible publication | Repair, normalize, or replace the diagnosis or draft |

### 5.1 Gap ownership and response surfaces

An unresolved diagnosis must preserve why the answer is incomplete and who
owns the next action. It must not collapse every unsuccessful investigation
into a generic `insufficient evidence` conclusion. The following are semantic
categories derived from existing classification, execution, and diagnostic
facts; they are not new parallel wire fields:

| Condition | Meaning | Next-action owner | Customer clarification |
| --- | --- | --- | --- |
| Provider execution failed or degraded | Authentication, readiness, parameter normalization, transport, query execution, or orchestration did not complete the intended internal read | Support or the applicable Provider/system owner | No request for the same internally queryable data |
| Provider metric query completed with a verified sparse empty | No matching sparse event was returned under a trusted target, window, metric, and selector contract | Scenario Diagnostic Agent decides whether that narrow absence is load-bearing | Only when a genuinely customer-owned scope ambiguity remains |
| Provider metric query completed with an unexplained or unclassified empty | No series was returned, but selector/label correctness or normal sparsity is not established; one same-round bounded validation has already run for an expected baseline | Support treats it as an explicit gap, never counter-evidence, and uses an authorized alternative surface only when load-bearing | Only when a genuinely customer-owned scope ambiguity remains |
| Non-metric Provider query completed with an empty result | No matching observation was returned for the exact queried entity, window, operation, and filters | Support first verifies scope and uses an already authorized alternative surface when load-bearing | Only when a genuinely customer-owned scope ambiguity remains |
| Provider completed but causal linkage remains unresolved | Facts were acquired, but they do not establish the required identity, mechanism, impact, recovery, or causal chain | Support continues internal diagnosis unless the missing discriminator is customer-owned | Ask only for the smallest customer-owned discriminator |
| Required customer context is absent | The missing fact describes the customer's application, action, client-side observation, or another fact Support cannot retrieve | L1 asks the customer | Yes, one focused question that explains what it will distinguish; because the customer must be asked, final `decision=human_required` |

Metrics, TopSQL, Slow Query, Statements, component logs, topology, and
node-to-cluster mapping are Support-owned when the selected Provider supports
them. A failed or empty internal lookup does not transfer ownership of that
data to the customer. In particular, `requestedContext` and
`clarificationSimulation` must not ask the customer to provide an internally
queryable artifact merely because its Provider query failed, timed out, or
returned no rows.

The Scenario Router owns this classification and the resulting next action. It
must preserve every valid observation from successful queries, distinguish
`failed` from `empty`, and decide whether the unresolved discriminator is
Support-owned or customer-owned. The Final Response Agent may improve the
wording of the selected response surfaces, but it must not change that owner,
turn an internal failure into customer clarification, or reduce the result to a
generic evidence-gap statement.

The customer-facing response should contain:

- the strongest facts and narrow conclusions already established;
- the exact conclusion that remains open, stated as an investigation boundary
  rather than a generic `insufficient evidence` verdict;
- Support's next action when the remaining work is internal;
- one focused question only when a customer-owned fact is required.

When the customer explicitly asks about the status, consolidation, recovery,
or intervention history of same-organization support tickets already supplied
in the bounded input, those tickets are Support-owned evidence. The response
answers that question from their cutoff-bounded history before requesting
unrelated diagnostic detail. Absence of a documented intervention may be
reported as such but is not proof of natural recovery; checking for an
undocumented internal action remains a Support-owned next step and does not
populate `requestedContext`.

It should not volunteer internal Provider names, query errors, escalation
routing, or a statement that the customer does not need to provide Metrics or
logs. Those details are unnecessary unless they directly answer a customer
question. It must not say or imply that data does not exist when the internal
query did not complete.

The internal human handoff should contain:

- the exact Support-readable region and cluster name when a Wetech route
  resolved a target and reached Provider acquisition; this is rendered without
  the machine `wetech:` target-reference prefix and remains absent from the
  customer message;
- facts and conclusions already established, with their entity and window;
- each load-bearing query outcome as completed, empty, or failed;
- the exact unresolved diagnostic boundary and its owner;
- the next internal query, retry, or alternative evidence surface;
- the escalation target and trigger when the failure belongs to Auto-oncall,
  Clinic, Wetech, Manus, or another system owner;
- any genuinely customer-owned question that remains, without requesting data
  Support can retrieve.

The target-only acquisition case is intentionally more compact. When no
diagnostic Provider evidence was acquired and the only blocker is identifying
which actual cluster a ticket alias refers to, Support does not need a future
query inventory or escalation tree. The internal message tells Support to
confirm the actual cluster and then invoke a fresh continuation through a real
internal ADF `@Auto Oncall` mention that includes the cluster name. This is a
next-action projection of the same unresolved boundary, not a new execution
field or a customer clarification.

SQL Digest handling, OP identifier handling, transient fault-domain
completeness, workload attribution, monitoring semantics, capacity diagnosis,
mitigation, severity, and handoff must be complete in Scenario Router
reconciliation. They are not post-Final-Response correction work. SQL/Digest request semantics
are not inferred with a publication regex on the direct path either: a request
for incident time that mentions an existing Digest is not a request for that
Digest. The selected semantic answer owner receives the supplied identity. After Final
Response, deterministic code may parse structure and enforce true disclosure,
tenant, destructive-action, privileged-promise, commercial/policy, and
publication-eligibility boundaries; it must not run another Agent rewrite or
replace the diagnosis for semantic consistency.

Evidence quantity is not a stricter completion gate. When a historical event
has recovered and the Scenario causal briefs support a useful bounded
conclusion, impact statement, safe advice, and no human-only action, the Router
normally returns `internal_only` while stating the remaining deeper RCA
boundary without promising another Support check. It must not promote the
ticket to `human_required` solely because a new query exposed another
non-load-bearing uncertainty or exact peak alignment is unavailable. If either
message instead assigns a load-bearing query, check, retry, follow-up, or
escalation to Support, that is required human handling and the Router must set
`decision=human_required`, even when `requestedContext=[]` and clarification is
false. Customer-owned missing context that still triggers a question
uses the L1 fallback and therefore becomes `human_required`. Safety, privileged
operations, severe active incidents, load-bearing internal evidence that only
Support can continue acquiring, and
explicitly human-owned mitigation remain valid `human_required` boundaries.

The final state combinations are:

| Remaining next action | Required final state |
| --- | --- |
| No load-bearing gap remains | `decision=internal_only`, `requestedContext=[]`, clarification false |
| A customer-owned fact is required and the customer message asks for it | `decision=human_required`, non-empty focused `requestedContext`, clarification true |
| A load-bearing internally queryable fact could not be acquired and Support must take over | `decision=human_required`; do not request the same fact from the customer |
| Safety, privileged action, severe active incident, or authorization requires a person | `decision=human_required` independently of clarification |

If a classification-time `missingKey` is resolved from authorized evidence,
the internal message records how it was resolved and the final requested
context stays empty. If it remains unresolved and customer-owned, the customer
message asks for it, clarification stays required, and the result is
`human_required`. The Router must not leave
`missingKeys` unresolved while silently returning a final-answer-shaped
customer message.

A complete automatic answer therefore requires all of the following:

```text
decision = internal_only
requestedContext = []
clarificationSimulation.required = false
customerReplyMarkdown is non-empty and within the publication size limit
```

A clarification message instead requires:

```text
decision = human_required
requestedContext contains only the smallest customer-owned discriminator
clarificationSimulation.required = true
customerReplyMarkdown asks one focused question
internalHandoffMarkdown records why that question is customer-owned
```

An affirmative canonical recommendation that Support evaluate temporary
backend scale-out forces `decision=human_required`. Merely selecting a capacity
scenario, crossing a utilization threshold, or noting scale-out as a
hypothetical option does not. Service-tier ownership,
control-plane responsibility, and the scale-out instruction belong only in the
internal `internalHandoffMarkdown` handoff. The customer draft may state that
Support is internally evaluating a safe temporary mitigation, but must not
expose the tier/responsibility mapping or promise the action.

## 6. Customer-visible publication

Customer publication remains limited by the configured cohort, scenario
allowlist, Bot Assignment trigger, idempotency claim, final validator, and Jira
public-comment write path. Cohort admission is the union of explicit Account
Alias, exact org ID, Jira project key, and typed Cloud org-region lists. A Cloud
org-region match requires both a non-empty typed `orgId` and the exact normalized
`SupportCase.tidbCloudOrgRegion` value read from Jira
`customfield_12841`; region text does not replace `orgId` as the Cloud identity
owner. The staging APAC cohort uses `projectKey=APID` for OP tickets and
`tidbCloudOrgRegion=APAC` for typed Cloud tickets.

Both of these resolution modes may become publication candidates:

### `direct_answer`

The final answer must satisfy the completion contract in section 5. No Provider
execution is required.

### `evidence_assisted`

The final answer must satisfy section 5 and the actual execution must satisfy:

```text
execution.evidenceAcquisition.status = complete
execution.evidenceAcquisition.provider = scenarioClassification.evidenceProvider
execution.evidenceAcquisition.providerCapabilityVerified = true
execution.evidenceAcquisition.failureCodes = []
```

`clarification_needed` and `skip` are not publication candidates. A
`human_required` result is never a final-answer candidate, but it may become a
customer progress-update candidate when all of the following hold:

```text
scenarioClassification.resolutionMode = evidence_assisted
execution.evidenceAcquisition.provider = scenarioClassification.evidenceProvider
scenarioClassification.missingKeys = []
requestedContext = []
clarificationSimulation.required = false
no hard diagnostic risk flag is present
customerReplyMarkdown is non-empty and within the publication size limit
```

Unlike a final evidence-assisted answer, a progress update does not require the
Provider execution to be complete. A failed or degraded attempt is exactly one
case in which Support may need to report established facts and continued
internal investigation without transferring the data request to the customer.
The selected Provider must still match the execution record so an unattempted
or differently routed investigation cannot be described as progress.

The existing Bot Assignment, cohort, scenario allowlist, Customer Reply Gate,
validator, public-write preflight, and delivery claim still apply. A
`human_required` direct answer, hard-risk result, customer clarification, empty
draft, provider mismatch, or ineligible trigger/cohort remains internal-only.
The validator treats the customer text as a progress update and rejects a final
root-cause claim, production go-ahead, privileged-action promise, or existing
disclosure/tenant/commercial boundary violation.

Final Response always returns the paired customer and internal messages. For
every published `human_required` progress update, live automation also creates
or updates a separate Jira internal comment with `public=false`. Whenever the
customer message is not actually written for any reason, live automation writes
the stable internal comment with distinct `Customer message` and `Internal
message` sections so the suggested customer wording and human context are both
preserved. The internal section carries the section 5.1 query outcomes,
unresolved boundary, owner, next internal action, and escalation target. Public
delivery and the stable internal comment use independent idempotency, so a
retry neither duplicates the customer message nor loses the internal message.
A final `decision=internal_only` publication may continue to omit the redundant
internal Jira comment after the customer write succeeds; both messages remain
in the canonical run and replay artifacts.

## 7. Risk ownership

`riskFlags` describe observed risk; they do not replace intent, final decision,
or final-draft safety checks. Ordinary product guidance may legitimately discuss
production scope, upgrade effects, configuration side effects, and query
correctness risks.

Informational guidance and operational ownership are separate. A customer request
for instructions to configure or validate its own setting does not become a
privileged Support operation merely because the setting has acknowledged
availability, durability, or performance trade-offs. When execution, approval,
or an unresolved boundary remains human-owned, the semantic answer owner still
preserves established product facts and independently verified subanswers,
including bounded steps, prechecks, verification, rollback, and risk caveats. It
isolates the unresolved or approval-dependent part and does not turn guidance
into a claim that the production change is safe to run now.

Human handling is required when the actual boundary is privileged execution,
destructive mutation, sensitive disclosure, cross-org data, active severe
incident ownership, or another explicit hard boundary. A token such as
`production` inside a non-operative flag, including `production_cluster` or
`production_excluded`, is not sufficient on its own.

Historical replay does not own an active incident. Historical severity flags
such as `urgent_incident` therefore remain Router diagnostic context and do not
create a monotonic safety floor. True safety flags such as data risk, secrets,
cross-org exposure, and destructive or privileged operations remain hard in
historical and live inputs.

Jira workflow and historical-handling labels such as `Escalated`, `mitigated`,
`resolved`, and `closed` are also Router timeline context. They do not prove a
current severe incident, safety risk, privileged operation, or required human
handoff and must not by themselves change a historical replay to
`human_required`.

When Router-selected product knowledge defines an alert's source quantity or
aggregation, the Router may explain firing only from an equivalent entity- and
time-aligned measurement. A different quantity, such as process RSS divided by
advertised capacity, cannot reproduce or negate host or cgroup utilization and
cannot select the alerting node. Missing configured threshold or duration is a
narrow evidence boundary, not by itself a reason to discard an otherwise
supported alert explanation.

A frozen historical firing-alert event is direct evidence that the actual
configured rule fired at that time. A later Provider reconstruction below the
reported threshold contradicts that event only when the same rule expression,
labels, aggregation, sample coverage, and firing interval are proven. Otherwise
the difference is a Support-owned reconstruction or monitoring-semantics gap:
it cannot identify an alerting node from another metric, become customer
requested context, or by itself force `human_required`. For a recovered
historical case without a safety boundary or load-bearing production action,
the Router keeps `internal_only` and preserves the exact Support follow-up.

For a customer-specific managed alert topic, an exact managed alert name or
unambiguous alert text may establish topic applicability when the ticket has
the required typed environment boundary but Jira omits Account Alias. A broad
resource symptom without that alert identity is not sufficient. The Router
still owns semantic selection from the bounded candidates; no downstream Agent
may infer customer applicability or select the topic.

The publication gate rejects concrete hard-risk flags. It must not replace
that bounded check with either “any risk flag” or a generic substring match for
`production`.

The customer publication validator inspects only the normalized final draft and
visible customer intent. It remains fail-closed for secrets, internal-only data,
cross-customer information, authorization bypass, destructive abuse,
privileged-action promises, and unauthorized commercial or policy commitments.

## 8. Historical compatibility

Historical Gate details, run workspaces, and evaluation fixtures may contain the
obsolete `evidenceRequired` or execution `required` fields, and may contain an
`evidenceProvider=investibook` route. Historical CDC classifications may also
contain `missingKeys=[cdc_configuration_meta]` and
`riskFlags=[cdc_configuration_meta_unavailable]`. Readers may ignore obsolete
extra fields and read the historical Provider value so historical evidence
remains usable. New classifier schemas, classifications, routing decisions,
workspaces, Gate details, execution payloads, evaluation traces, and publication
decisions must not emit or depend on the obsolete fields, CDC metadata hard
stop, or Investibook.

## 9. Core implementation map

- `src/types.ts`: typed classification, execution, and result contracts.
- `src/handling-contract.ts`: shared derivation of Provider-route eligibility.
- `src/llm-scenario-classifier.ts`: LLM classification schema and structural
  invariants.
- `src/scenario-classifier.ts`: deterministic normalization and routing policy.
- `src/auto-coverage-gate.ts`, `src/auto-config.ts`: coverage admission.
- `src/diagnostic-context.ts`, `src/diagnostic-pipeline-policy.ts`,
  `src/clinic-targets.ts`, `src/runner.ts`: Provider selection, bounded Clinic
  target resolution, and actual evidence execution.
- `src/diagnostic-scenarios.ts`, `src/clinic-evidence.ts`: Scenario Router
  target-set contract and shared materialization.
- `src/clinic-evidence-batch.ts`: local Codex SDK compatibility Provider
  Executor; it is active compatibility code, not the Agent9 Managed Clinic
  runtime owner.
- `tools/agent9-auto-oncall/managed-clinic/`: Agent9 Managed Clinic Provider
  Executor source used by staging runtime.
- `src/diagnostic-preflight.ts`, `src/analysis-service.ts`: final human-review
  enforcement and result normalization.
- `src/primary-analysis-policy.ts`: direct-path semantic analysis policy;
  product facts remain in `product-knowledge/` and presentation remains in
  `src/skills/support-reply-format.ts`.
- `src/customer-replies.ts`, `src/auto-analysis.ts`: publication candidacy,
  validation, idempotency, and Jira write.
- `src/recent-evaluation.ts`, `src/recent-evaluation-evidence-trace.ts`:
  evaluation of the persisted execution chain.

## 10. Required change procedure

Before modifying any file listed in section 9 or changing an equivalent core
path:

1. Read this document and the applicable sections of `AGENTS.md`.
   If the change produces or consumes either response message, also read
   `DUAL_MESSAGE_CONTRACT.md`.
2. Identify which field owns the fact being changed.
3. Update this document when field meaning, legal combinations, stage ownership,
   or publication criteria change.
4. Update the classifier, deterministic normalization, runtime consumers, and
   contract tests together. Do not patch only one consumer.
5. Verify that new payloads contain no obsolete parallel field.
6. For rollout changes, follow the app-delivery and live verification contract
   in `AGENTS.md`.
